回溯法实现格雷码

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3

10 - 2

回溯法可实现,但是不符合LeetCode的答案顺序。

【思路】每一位要么是1,要么是0。

class Solution {
public:
//正确的,但不符合输出顺序。
   void bits(int start, int n, vector&re, int label[])
    {
       if(start==n){
       int c = 0;
       for(int i = 0; i < n; i++)
       {
           int a = label[i] * pow(2.0,i);
           c += a;
       }
       re.push_back(c);
       return;
       }
       label[start] = 0;
       bits(start+1, n, re, label);
       label[start] = 1;
       bits(start+1, n, re, label);
    }

    vector grayCode(int n) {
        vector re;
        if(n==0)
        {
            re.push_back(0);
            return re;
        }
        int label[n] = {0};
        bits(0, n, re, label);
        return re;
    }
};


你可能感兴趣的:(【数据结构与算法】,【LeetCode】)