Tuesday, June 28, 2016

89. Gray Code

I solved this problem by observing some examples. For gray code that has 4 bits,
0 0 0 0
0 0 0 1
=====
0 0 1 1
0 0 1 0
=====
0 1 1 0
0 1 1 1
0 1 0 1
0 1 0 0
=====
1 1 0 0
1 1 0 1
1 1 1 1
1 1 1 0
1 0 1 0
1 0 1 1
1 0 0 1
1 0 0 0
From the example above, I find that the gray code can be generated one bit by one bit. For a new significant bit, the gray code can be generated by the previous result in reverse order.

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

No comments:

Post a Comment