Gray Code

Q:

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.

格雷码:任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码

典型格雷码是首尾相连的,即首尾的代码也是只差 1位的。

A: f(i)表示n==i时的格雷码序列,那么f(i+1)的个数是f(i)的2倍,而且f(i)序列也是属于f(i+1)的。

举个例子n==1,f(1): 0,1

n==2    f(2) : 00 01 11 10 也就是 f(1)的顺序列加上前缀0---->得到前半部分序列

                  f(1)的逆序列加上前缀1---->得到后半部分序列

也就是说  f(i+1)可以由f(i)得到。

graycode用int表示的话,那么f(i+1)的前半部分与f(i)相等,后半部分可以由f(i)逆序列的每个元素异或1<<(i-1)得到(即加上前缀1之后的int值)

    vector<int> grayCode(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> res;
        
        res.push_back(0);
        
        for(int i=1;i<=n;i++)
        {
            for(int j=res.size()-1;j>=0;j--)
                res.push_back(res[j]^(1<<(i-1)));
        }
        
        return res;
        
    }

  

posted @ 2013-09-19 23:20  summer_zhou  阅读(286)  评论(0)    收藏  举报