We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 20bb984 commit 7fdb22eCopy full SHA for 7fdb22e
C++/gray-code.cpp
@@ -0,0 +1,30 @@
1
+// Time: (2^n)
2
+// Space: O(1)
3
+
4
+class Solution {
5
+public:
6
+ vector<int> grayCode(int n) {
7
+ vector<int> result = {0};
8
+ for (int i = 0; i < n; ++i) {
9
+ for (int j = result.size() - 1; j >= 0; --j) {
10
+ result.emplace_back(1 << i | result[j]);
11
+ }
12
13
+ return result;
14
15
+};
16
17
18
19
+// Proof of closed form formula could be found here:
20
+// http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code
21
+class Solution2 {
22
23
24
+ vector<int> result;
25
+ for (int i = 0; i < 1 << n; ++i) {
26
+ result.emplace_back(i >> 1 ^ i);
27
28
29
30
0 commit comments