forked from kedebug/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrayCode.cpp
More file actions
29 lines (27 loc) · 713 Bytes
/
GrayCode.cpp
File metadata and controls
29 lines (27 loc) · 713 Bytes
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
class Solution {
public:
vector<int> grayCode(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> gray_code;
for (int i = 0; i < (1 << n); i++)
gray_code.push_back((i >> 1) ^ i);
return gray_code;
}
};
// More comprehensible solution
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result(1, 0);
for (int i = 0; i < n; i++) {
int curr = result.size();
while (curr) {
curr--;
int x = result[curr];
result.push_back((1 << i) + x);
}
}
return result;
}
};