2016年2月25日 星期四

LEET 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.



把幾個case寫出來會發現

先是0--> 0->00    
                1   01
                     11
                     10

會發現在第三個bit之前  是倒過來看的

像是下面的 紅色跟藍色剛好是倒過來
所以 每次算好一個bit  下一個bit就是把之前的倒過來+上2的倍數就好
000   0
001   1
011   3
010   2

110   2+2
111   2+3
101   2+1
100   2+0







 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> ans;
        ans.push_back(0);
        for(int i=1;i<=n;i++){
            int factor=1<<(i-1);
            for(int j=ans.size()-1;j>=0;j--){
                ans.push_back( ans[j]+factor );
            }
        }
        return ans;
    }
};

沒有留言:

張貼留言