LeetCode题解:Gray Code

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.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

思路:

初次看到的时候觉得可能是要做图搜索的样子。但是事实上并不那么复杂,只要找到下一个未访问过的数就可以了。这里用一个简单的异或操作就可以flip一个位:x ^= (1 << bit)。另外用了一个set来保存已经访问过的数字。set一般是通过hash的方法来搜索的,因此平均花费的时间是O(1)。而map的key搜索则要O(log n),因为map的实现通常是基于红黑树的。

题解:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> ret;
        set<int> usedval;
        auto flip = [&](int k, int bit) -> int
        { return k ^ (1 << bit); };
         
        queue<int> visit;
        visit.push(0);
        while(!visit.empty()) 
        {
            auto front = visit.front();
            visit.pop();
            
            ret.push_back(front);
            usedval.insert(front);
            
            // now check possible choices
            // we have to avoid the sgn bit
            for(int i = 0; i < n; ++i)
            {
                int newval = flip(front, i);
                if (usedval.find(newval) != usedval.end())
                    continue;
                else
                {
                    visit.push(newval);
                    break;
                }
            }
        }
        return ret;
    }
};


你可能感兴趣的:(LeetCode)