[leetcode 89] Gray Code---实现格雷码

来源:互联网 发布:淘宝psn点卡 编辑:程序博客网 时间:2024/05/21 17:26

Question:

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 - 001 - 111 - 310 - 2

分析:

以n = 3为例:

000

001

011

010

-------

110

111

101

100

如上所示,根据格雷码规则,可以看出,前半部分与n=2时候的结果一样,将前半部分从下往上看,后半部分从上往下依次是最高位多个1,其余均与上半部分对称。

所以后半部只要将前半部分从下往上依次加上2的(n-1)次方即可。


代码如下:

<span style="font-size:14px;">class Solution {public:    vector<int> grayCode(int n) {        vector<int> res;        vector<int> pre;        if(n == 0){            res.push_back(0);            return res;        }        if(n == 1){            res.push_back(0);            res.push_back(1);            return res;        }        pre = grayCode(n-1);        for(int i : pre){            res.push_back(i);        }        int t = (int)pow(2,n-1);        for(int i = pre.size()-1; i >= 0; --i){                        res.push_back(pre[i]+t);        }        return res;    }};</span>


0 0
原创粉丝点击