Gray Code
given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2[0,2,3,1] is also a valid gray code sequence according to the above definition.given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2[0,2,3,1] is also a valid gray code sequence according to the above definition. # 解法 1,找规律
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = []
res.append(0)
for i in range(n):
addend = 1 << i
size = len(res)
for i in range(len(res) - 1, -1, -1):
res.append(res[i] | addend)
return res # 解法 2,数学公式,第i个gray code为(i >> 1)^ i
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = []
num = 1 << n # 例如当n=3时,一共有2^3=8个gray code,1<<3=8
for i in range(num):
res.append((i >> 1) ^ i)
return res