-
Notifications
You must be signed in to change notification settings - Fork 257
/
gray-code.cpp
38 lines (36 loc) · 893 Bytes
/
gray-code.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time: (2^n)
// Space: O(1)
class Solution {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> result = {0};
for (int i = 0; i < n; ++i) {
for (int j = result.size() - 1; j >= 0; --j) {
result.emplace_back(1 << i | result[j]);
}
}
return result;
}
};
// Time: (2^n)
// Space: O(1)
// Proof of closed form formula could be found here:
// http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code
class Solution2 {
public:
/**
* @param n a number
* @return Gray code
*/
vector<int> grayCode(int n) {
vector<int> result;
for (int i = 0; i < 1 << n; ++i) {
result.emplace_back(i >> 1 ^ i);
}
return result;
}
};