Gray Code

Gray Code

题目描述:

给定一个整数n,要求返回n位格雷码的对应的数字的结果。

例子:

具体描述见LeetCode89

解题思路:

对于n位的格雷码结果,我们从末尾开始对每个结果加上1左移n-1位的结果然后添加到旧的结果中即可得到n+1位的格雷码的结果。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1, 0);
for (int i = 0; i < n; i++){
int cur = res.size();
while(cur){
cur--;
int temp = res[cur];
temp += (1 << i);
res.push_back(temp);
}
}
return res;
}
};