[leetcode] Gray Code 解题报告

题目链接:https://leetcode.com/problems/gray-code/

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.


思路:给定一个数n,则总共会有2 的n次方个数。由于每次只能变化一位,并且只有n位,因此可以让当前结果异或一个2^i,(0 < i < n),并且设置一个hash表,判断当前异或的结果是否存在。如此即可排列出所有结果。具体代码如下:

class Solution {
public:
    void DFS(vector<int>& result, vector<bool>& hash, int n, int value)
    {
        for(int i =0; i< n; i++)
        {
            int tem = (int)pow(2, i) ^ value;
            if(!hash[tem])
            {
                hash[tem] = true;
                result.push_back(tem);
                DFS(result, hash, n, tem);
            }
        }
    }
    vector<int> grayCode(int n) {
        vector<bool> hash(pow(2,n), false);
        vector<int> result;
        result.push_back(0);
        hash[0] = true;
        DFS(result, hash, n, 0);
        return result;
    }
};

而实际上有一种更为简单的方法,利用gray code的性质

class Solution {
public:
    vector<int> grayCode(int n) {
        int len = 1 << n;
        vector<int> result;
        for(int i = 0; i < len; i++)
            result.push_back(i ^ (i>>1));
        return result;
    }
};

参考:https://leetcode.com/discuss/67558/11-lines-c-solution-4ms





你可能感兴趣的:(LeetCode,算法,回朔)