Gray Code

来源:互联网 发布:淘宝企业店铺如何贷款 编辑:程序博客网 时间:2024/05/21 17:34

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

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.我的想法。

先是加入0,1。 然后对0,1从前往后的后面加0,再对0,1进行从后往前的加1.即 00,10,11,01.

以此类推,再在以上四个里面,先是从前往后挨个在最后加0,再是从后往前挨个加1.

class Solution {public:    vector<int> grayCode(int n) {        vector<vector<int>> res,vec;        vector<int> v;        v.push_back(0);        if(n==0)        return v;        vec.push_back(v);        v.push_back(1);        if(n == 1)        return v;        v.clear();        v.push_back(1);        vec.push_back(v);        for(int i = 1; i < n; i++){            res.clear();            for(auto& j:vec){                 j.push_back(0);                res.push_back(j);                j.pop_back();            }            for(int i = vec.size()-1; i >=0; i--){                vec[i].push_back(1);                res.push_back(vec[i]);            }            vec.clear();            vec.insert(vec.end(),res.begin(),res.end());        }        v.clear();                for(int k = 0; k < res.size(); k++){            int sum = 0;            for(int p = res[k].size()-1; p >=0 ; p--){                sum = sum * 2 +res[k][p];            }            v.push_back(sum);        }        return v;    }};

2.别人的代码

方法跟我一样,只不过他很巧妙的利用了移位。

vector<int> grayCode(int n) {        vector<int> res;        int bits = 1;        int ntmp=0;        res.push_back(0);        for(int i=0;i<n;i++)        {            bits=1<<i;            for(int j = res.size()-1;j>=0;j--){                ntmp = res.at(j)+bits;                res.push_back(ntmp);            }        }        return res;    }


0 0
原创粉丝点击