Skip to content

Commit 7fdb22e

Browse files
authored
Create gray-code.cpp
1 parent 20bb984 commit 7fdb22e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/gray-code.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
// Time: (2^n)
18+
// Space: O(1)
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+
public:
23+
vector<int> grayCode(int n) {
24+
vector<int> result;
25+
for (int i = 0; i < 1 << n; ++i) {
26+
result.emplace_back(i >> 1 ^ i);
27+
}
28+
return result;
29+
}
30+
};

0 commit comments

Comments
 (0)