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.
思路:最开始用的方法是递归,例如,n=3可以看成是n=2的结果尾巴添加n=2的结果加上2的2次方的倒序。
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
if(n==0){
result.push_back(0);
return result;
}
if(n==1){
result.push_back(0);
result.push_back(1);
return result;
}
result=grayCode(n-1);
int size=result.size();
int i=size-1;
int temp;
for(;i>=0;--i){
temp=size+result[i];
result.push_back(temp);
}
return result;
}
};
第二种方便的思路是将二进制码右移一位与本身异或即可得到结果