题目名称
Gray Code—LeetCode链接
描述
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=1时:graycode=[0,1],二进制表示为[0,1];
n=2时:graycode=[0,1,3,2],二进制表示为[00,01,11,10];注意这里并不是0,1,2,3;
n=3时:graycode=[0,1,3,2,6,7,5,4],前四个数与n=2时完全相同,在分析二进制表示:
n=2
十进制:0, 1, 3, 2
二进制:00,01,11,10
n=3
十进制:0, 1, 3, 2, 6, 7, 5, 4
二进制:000,001,011,010,110,111,101,100
000,001,011,010
100,101,111,110
6比2多4,7比3多4,5比1多4,4比0多4
由此得到一个递推公式,n+1中的元素可以这样得到:
n+1中的graycode码个数是n中的两倍,首先复制一份n中的元素,然后按照n中的元素从后往前依次增加2的n次方,加入到n+1中。
这样保证了相邻元素之间只有一个位的数字不同。
C++代码
vector<int> grayCode(int n) {
vector<int> res;
if(n<0)
return res;
if(n==0){
res.push_back(0);
return res;
}
res.push_back(0);
res.push_back(1);
for(int i=1;i<n;i++){
vector<int> temp(res);
//这里是计算2的i次方,将1向坐位移i个单位
int add = 1<<i;
int a=0,b=temp.size()-1;
for(b;b>=a;b--){
temp.push_back(temp[b]+add);
}
res = temp;
}
return res;
}
总结
采用迭代法。