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
格雷码!!想起了数电中学过的,想起了卡诺图,还会画。。嗯
先放个二元的格雷码感受一下:
00 - 0
01 - 1
11 - 3
10 - 2
可以看到前面一半都是0开头,后面的是1开头,除去开头的部分,剩下的对称。
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n==0:return [0]
if n==1:return [0,1]
l1=self.grayCode(n-1)
def int_to_string(x,n):
y=bin(x)[2:]
if len(y)<n:
y='0'*(n-len(y))+y
return y
return l1+[int('1'+int_to_string(i,n-1),2) for i in l1[::-1]]
上文中,子函数的作用是把 整数变成长度为n的二进制的字符串,不能直接用bin(),因为对于四元的格雷码,0得有0-000 1-000;而不是0-0 1-0.
讲上诉代码写成迭代的形式的话,如下:
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n==0:return [0]
if n==1:return [0,1]
l=[0,1]
def int_to_string(x,n):
y=bin(x)[2:]
if len(y)<n:
y='0'*(n-len(y))+y
return y
for i in xrange(1,n):
l+= [int('1' + int_to_string(j, i), 2) for j in l[::-1]]
return l
但是还不够好,是吧,因为只看到了现象没有看到本质。
最开始能看到:
00 - 0
10 - 2
是只有二进制的首位发生了变化,所以写了上诉的两个解法,但是应该深入考虑一下,首位的变化就意味着: 差值是2**(n-1)
这样看前面的string和int就很啰嗦啦~~
于是:
95.56%
class Solution(object):
def grayCode(self, n):
if n == 0: return [0]
result = [0, 1]
for i in xrange(1, n):
result += [x + 2**i for x in result[::-1]]
return result
当然也可以用移位来做:
67.18%
class Solution(object):
def grayCode(self, n):
if n == 0: return [0]
result = [0, 1]
for i in xrange(1, n):
y=1<<i
result += [x + y for x in result[::-1]]
return result