1.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.
解读
格雷码序列:在一系列数字对应的二进制形式下,相邻两个数字只有一位是不同的,题目要求从第0开始
2.Solution
#Turn back;03-23
#Time:O(n*2)
class Solution(object):
def grayCode(self, n):
code=[0]
for i in range(n):
code+=map(lambda x:x+2**(i),code[::-1])
return code
代码说明
以n=2时,【0,1,3,2】是合法的格雷码序列,这时候对应的二进制是
【000,001,011,010】如果再添加一个1,可以按照倒叙的方式添加,前面这四个是相邻的且合法,倒叙之后在最前面添加一个数字仍然是连续合法的;总结一下流程:
for i=[0:n)
1:倒叙
2:每个数字加上一个数(2^n)
3:合并