【一天一道LeetCode】#89. Gray Code

时间:2021-09-03 08:06:05

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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,生成n位的格雷码。

之前做过格雷码的题目,每次都在n-1位格雷码的后面加上0和1组成n位格雷码。

题目中提到只认示例中给定的格雷码顺序。

因此,很容易找到规律,每次从n-1位格雷码的尾部往前,依次加上2的n-1次方,就得到新的n位格雷码。

代码如下:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> ret;
        if(n==0) {//为0的时候需要特殊处理
            ret.push_back(0);
            return ret;
        }
        for(int i = 0 ; i < n ; i++)
        {
            if(i==0)//这里表示1位格雷码
            {
                ret.push_back(0);
                ret.push_back(1);
            }
            else
            {
                for(int j = ret.size()-1 ; j >=0 ; j--)//每次从n-1位格雷码的尾部向前,一次加上2的n-1次方得到新的格雷码
                {
                    ret.push_back(pow(2,i)+ret[j]);
                }
            }
        }
        return ret;
    }
};