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
问题描述:gray code是一种二进制数字
系统,在这个系统中,两个相邻的数字之间只有一位不同。
给定一个非负整数n,n表示总共的位数,请打印出该gray code的序列,该序列必须以0开始。
后面给了一个n为2时的例子,如果要是能够利用这个例子来构造n值的序列就好了。通过分析可以得出,n的序列可以通过n-1的序列构造,将n-1的序列反向添加到原来的序列后面,
再原来的序列前加0,后来的序列前加1,其实也可以在后面加,但是OJ采用的是在前面加。
class Solution {
public:
vector grayCode(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector vec;
if(n == 0) {
vec.push_back(0);
return vec;
}
vec = grayCode(n-1);
int i = 0;
for(i = vec.size()-1; i >= 0; i--) {
vec.push_back(vec.at(i) | (1<<(n-1)));
}
return vec;
}
};