Gray Code (LeetCode)

Question:

https://oj.leetcode.com/problems/gray-code/

 

解法1:

n位的gray code V[n]相当于n-1位的gray code V[n-1]分别再加上第n位的0和1。为保持gray code的特性,在加0结束转换到加1的时候,V[n-1]从后往前加。

 

解法2:

利用gray code的特性,2n内的数可分为两半,前后两半除了最高位不同,前半段是0,后半段是1,其余部分是镜像相同的。

所以求出2k内的gray code数列Vk后,后面2k的数等于VK的镜像加上2k

 

class Solution {
public:
    vector<int> grayCode(int n) {
        
        vector<int> result;
        result.push_back(0);
        
        for (int i = 1; i <= n; i++)
        {
            // result already have pow(2, i-1) elements
            GrayMirror(result);
        }

        return result;
    }
    
    void GrayMirror(vector<int>& result)
    {
        int count = result.size();  // count must be same as pow(2, k-1);
        int value = count;
        
        for (int i = count-1; i >= 0; i--)
            result.push_back(result[i]+value);
    }
    
    void grayBacktracking(vector<int>& result, int n)
    {
        if (n== 0)
        {
            result.push_back(0);
            return;
        }

        if (n == 1)
        {
            result.push_back(0);
            result.push_back(1);
            return;
        }
        
        vector<int> lower;
        gray(lower, n-1);
        
        for (int i = 0; i < lower.size(); i++)
        {
            result.push_back(lower[i]);
        }
        
        int value = 1 << (n-1);
        
        // start from lower.size()-1 to make sure 
        // the first value written to result before adding value
        // is same as the last value added above
        for (int i = lower.size()-1; i >= 0; i--)
        {
            result.push_back(lower[i]+value);
        }
    }
};

 

posted @ 2015-01-21 14:44  smileheart  阅读(317)  评论(0)    收藏  举报