# 089 gray code

### 89. Gray Code

A gray code sequence must begin with 0. ->简化了一点

def nextCode(curCode, res, n):
if curCode not in res:
res.append(curCode)
else:
return
if len(res) == pow(2,n):
return res
for i in range(n):
nCode = curCode[:]
nCode[i] = 1 if curCode[i] == 0 else 0
nextCode(nCode,res,n)

res = []
nextCode([0,0,0],res,3)
print res
#[[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 0, 1], [0, 0, 1]]



class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
def nextCode(curCode, res, n):
if curCode not in res:
res.append(curCode)
else:
return
if len(res) == pow(2,n):
return res
for i in xrange(n):
nCode = curCode[:]
nCode[i] = 1 if curCode[i] == 0 else 0
nextCode(nCode, res, n)

def listoVal(curCode,n):
val = 0
for i in range(n-1,-1,-1):
val += pow(2,i) * curCode[i]
return val

res = []
nextCode([0]*n, res, n)
# print res

val = []
for i in res:
val.append(listoVal(i,n))
return val


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

class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = [(i>>1)^i for i in range(pow(2,n))]
return results


apachecn/AiLearning