首页 > 代码库 > Gray Code
Gray Code
Problem:
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.
分析:
枚举2n种情况,对于每一个比特位,均可以做翻转与不翻转两种状态。从最低位开始到最高位,最低位不翻转,递归生成0,,最低位翻转,递归生成1。然后是次低位反转,递归生成3, 2。后面依次可以翻转低第3位,低第4位,等等。
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 string s(n, ‘0‘); 6 vector<int> result; 7 int cur = 0; 8 DFS(result, s, cur, n-1); 9 return result; 10 } 11 12 void DFS(vector<int> &result, string &s, int& cur, int idx) { 13 if(idx == -1) { 14 result.push_back(cur); 15 } else { 16 // do not flip 17 DFS(result, s, cur, idx-1); 18 19 // do flip 20 if(s[idx] == ‘0‘) { 21 s[idx] = ‘1‘; 22 cur += (1<<idx); 23 } else { 24 s[idx] = ‘0‘; 25 cur -= (1<<idx); 26 } 27 DFS(result, s, cur, idx-1); 28 } 29 } 30 };