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

 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 };

posted @ 2014-05-02 21:37  夏目家的猫咪老师  阅读(345)  评论(0编辑  收藏  举报