题目
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
解答
这就是离散数学里面一个格雷码的快速推导算法。。。
比如2位格雷码是00 01 11 10,这个数列奇数项左移后先加0再加1,偶数项左移后先加1再加0,按顺序组成的数列就是3位格雷码000 001 011 010 110 111 101 100。原理很简单,因为本来就是两两相邻之间差一位,现在按照这样操作,左移扩展一位,而新加的这一位又是01100110,这样原来每个数都扩展为相邻差一位,而原来相邻差一位的两个数之间加的是同样的一位数。
下面是AC的代码:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> ans;
vector<int> temp;
ans.push_back(0);
for(int i = 0; i < n; i++){
int length = ans.size();
temp.clear();
for(int i = 0; i < length; i++){
if(i % 2 == 0){
temp.push_back(ans[i] * 2 + 0);
temp.push_back(ans[i] * 2 + 1);
}
else{
temp.push_back(ans[i] * 2 + 1);
temp.push_back(ans[i] * 2 + 0);
}
}
ans = temp;
}
return ans;
}
};
119
原文地址:https://www.cnblogs.com/YuNanlong/p/8880839.html