标签:
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.
下面我们给出两种算法,第一种就是利用这种对称特征,较为复杂,第二种,利用对称和移位,在之前已经构造的格雷码的基础上,由下往上遍历已经建好的格雷码(假设码有i位),依次增加((1<<i)),并加入到格雷码序列中。相当于设置二进制序列的第i位为1.两种算法的代码如下:00 0111 10
vector<int> grayCode(int n) {
if(n==0)
{
vector<int> res(1,0);
return res;
}
if(n==1)
{
vector<int> res(2,0);
res[1]=1;
return res;
}
vector<int> mem(n,0);
vector<vector<int>> mem2;
mem2.push_back(mem);
mem[0]=1;
mem2.push_back(mem);
mem[1]=1;
mem2.push_back(mem);
mem[0]=0;
mem2.push_back(mem);
int lll=(1<<n);
int flag=1;
for (int i=4;i<lll;)
{
int len=mem2.size()-1;
flag++;
for (int j=len;j>=0;j--)
{
vector<int> temp=mem2[j];
i++;
temp[flag]=1;
mem2.push_back(temp);
if (i>=lll)
{
break;
}
}
}
mem.clear();
for (int i=0;i<mem2.size();i++)
{
int temp=0;
for (int j=0;j<n;j++)
{
temp+=mem2[i][j]*pow(2.0,j);
}
mem.push_back(temp);
}
return mem;
}vector<int> grayCode1(int n)
{
vector<int> res(1,0);
for (int i=0;i<n;i++)
{
int cur=res.size();
while(cur)
{
cur--;
int num=res[cur];
num+=(1<<i);
res.push_back(num);
}
}
return res;
}标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45793171