问题描述:
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位格雷码一共有2^(n+1) = 2^n * 2个码字,可分为前2^n个和后2^n个。
规律如下:
1、(n+1)位格雷码(grayCode(n+1))中的前2^n个码字等于:n位格雷码的
码字(grayCode(n))按顺序书写,加前缀0。
2、(n+1)位格雷码(grayCode(n+1))中的后2^n个码字等于:n位格雷码的
码字(grayCode(n))按逆序书写,加前缀1。
由于是二进制,在最高位加0跟原来的数本质没有改变,所以取得上一位算出的格雷码结果,再加上逆序加1的结果就是当前这位格雷码的结果。
例子:
n = 1时,[0,1]->[0,1]
n = 2时,[00,01,11,10]->[0,1,3,2]
n = 3时,[ 000,001,011,010 , 110,111,101,100]->[0,1,3,2,6,7,5,4]
当n=1时,0,1
当n=2时,原来的0,1不变,只是前面形式上加了个0变成00,01。然后加数是1<<1为10,依次:10+1=11 10+0=10。结果为:00 01 11 10
当n=3时,原来的00,01,11, 10(倒序为:10,11,01,00) 。加数1<<2为100。倒序相加为:100+10=110, 100+11= 111 ,100+01= 101 , 100+00= 100。结果为000 001 011 010 110 111 101 100.十进制大小即是:0,1,3,2,6,7,5,4。
递归求解
class Solution {
public:
vector<int> grayCode(int n) {
if(n==0)
{
vector<int> res;
res.push_back(0);
return res;
}
vector<int> pre = grayCode(n-1);
//(1)先把n-1位的格雷码放进结果数组(因为二进制在最高位加0与否没有影响)
vector<int> res(pre);
int npre = pre.size();
for(int i=npre-1;i>=0;i--)
{//(2)将把n-1位的格雷码逆序再与1<<n-1相加,最后放到结果数组
res.push_back((1<<n-1) + pre[i]);
}
return res;
}
};
当n=3时,输出结果:[0,1,3,2,6,7,5,4]
字符串形式:
#include<iostream>
#include<vector>
#include <string>
using namespace std;
class GrayCode {
public:
vector<string> getGray(int n) {
if(n==1)
{
vector<string> res;
res.push_back("0");
res.push_back("1");
return res;
}
vector<string> pre = getGray(n-1);
int npre = pre.size();
int ncur = npre * 2;
vector<string> res(ncur);
for(int i=0;i<npre;i++)
{
res[i] = "0" + pre[i];//前2^(n-1)个
res[ncur-i-1] = "1" + pre[i];//后2^(n-1)个
}
return res;
}
};
int main()
{
GrayCode g;
vector<string> res = g.getGray(3);
for(unsigned i=0;i<res.size();i++)
cout<<res[i]<<endl;
return 0;
}
结果:
000
001
011
010
110
111
101
100
Process returned 0 (0x0) execution time : 0.591 s
Press any key to continue.