-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsolve.cpp
47 lines (47 loc) · 913 Bytes
/
solve.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
39
40
41
42
43
44
45
46
47
#include <vector>
#include <string>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> grayCode(int n) {
return grayCode2(n);
}
private:
vector<int> grayCode1(int n) {
vector<int> result;
for (int i = 0; i < (1 << n); ++i) {
result.push_back(i ^ (i >> 1));
}
return result;
}
vector<int> grayCode2(int n) {
vector<int> result;
result.push_back(0);
for (int i = 0; i < n; ++i) {
int high = 1 << i;
for (int j = result.size() - 1; j >= 0; --j)
result.push_back(result[j] + high);
}
return result;
}
};
void print(vector<int> v)
{
cout << "[";
for_each(begin(v), end(v), [](int i){cout << i << ' ';});
cout << "]";
cout << endl;
}
int main(int argc, char **argv)
{
Solution solution;
int n;
while (cin >> n) {
print(solution.grayCode(n));
}
return 0;
}