【Leetcode】【Medium】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.

 

解题思路:

这道题相当于"穷举"n个0/1排列组合,涉及到排列组合,通常可以先考虑回溯法。

设ret表示返回的数字列表,ret初始为[0,],有两种思路:

1、循环遍历ret列表n次,每次对ret中每一个元素使用"<<"左移运算,并将左移运算后的结果加1,加入列表当中;

  即{0}->{0, 1}->{00, 10, 01, 11}->{000, 100, 010, 110, 101, 011, 111}->...

  即{0}->{0, 1}->{0, 2, 1, 3}->{0, 4, 2, 6, 1, 5, 3, 7} ...

2、取出ret中已有元素的值,并将其增加,将新值插入ret中,循环n次:

  {0}           取出每个元素加入1,并将结果加入列表     ->{0, 1}                ->{0, 1}

  {0, 1}       取出每个元素加入10,并将结果加入列表    ->{0, 1, 10, 11}            ->{0, 1, 2, 3}

  {10, 11}   取出每个元素加入100,并将结果加入列表   ->{0, 1, 10, 11, 100, 101, 110, 111} ->{0, 1, 2, 3, 4, 5, 6, 7}

 

但是这个该死的题目要求必须要按照Leetcode给定的顺序排列数字,就是必须{0, 1, 3, 2};

因此只能使用第二种方法,并且倒序取出已有元素;

代码:

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

 

posted @ 2015-04-13 21:27  胡潇  阅读(157)  评论(0编辑  收藏  举报