Gray Code
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.
n=3时,GrayCode是:
000
001
011
010
110
111
101
100
n 比特的格雷码,可以递归地从 n - 1 比特的格雷码生成。
n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如右图所示一般。
红色的最高位加一即保持不变。
蓝色的最高位加一;n = 1时原格雷码十进制加1 ; n = 2时 加2 ; n = 3时 加 4 ;n= 4时 加 8............
/**
* n位的格雷码的
* 前1/2
* 就是(n-1位的格雷码)
* 后1/2
* (将[n-1 位的格雷码 倒序 + 1<<i (i为当前的n-1) ] push进去就是)
*
**/
class Solution {
public:
//镜射排列
vector<int> grayCode(int n) {
int i,j,count,c;
vector<int> code;
//初始为0位
code.push_back(0);
for(i = 0;i < n;i++){
count = code.size();
c = 1 << i;
//添加镜面反射的那一部分(最高位加1)
//要反着遍历才能对称
for(j = count - 1;j >= 0;j--){
code.push_back(code[j] + c);
}
}
return code;
}
};