飘落的树叶

导航

[LeetCode]Gray Code

Description: 

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代表比特位数,求出在该比特位数下的格雷码,并且按照顺序输出他们的十进制数。

比如,给出n=2,返回[0, 1, 3, 2],他们代表的格雷码顺序为:

 

00 - 0
01 - 1
11 - 3
10 - 2

下面的note是说,其实格雷码有好多种顺序,因为只需要满足“相邻的数相差一个比特位”这个条件就可以了。不过目前这个系统只支持“正常”的格雷码顺序,请大家见谅。。。

  

解析:

有关格雷码,请参见:

http://en.wikipedia.org/wiki/Gray_code

讲得很清楚啦。另外其实一下两篇博客都讲的很好:

http://fisherlei.blogspot.com/2012/12/leetcode-gray-code.html

http://blog.csdn.net/worldwindjp/article/details/21536103

 

总之,按照http://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code

基本思路是有了。但是看到leetcode上的discuss,才想到其实空间是可以节省的:

在访问逆序那里,下标从最后一个数开始访问,一直访问到第一个数,便是逆序;另外,在二进制数最前面加上一个比特位1,相当于是加上了1<<n-1所代表的十进制数。

因此,C++代码:

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

 

 

posted on 2014-06-13 15:04  飘落的树叶  阅读(132)  评论(0)    收藏  举报