leetcode 每日一题 89. 格雷编码

找规律

思路:

格雷编码生成过程,G(i) = i ^ (i/2)

例如:

n = 3:

G(0) = 000,

G(1) =  1 ^ 0 = 001 ^ 000 = 001

G(2) = 2 ^ 1 = 010 ^ 001 = 011

G(3) = 3 ^ 1 = 011 ^ 001 = 010

G(4) = 4 ^ 2 = 100 ^ 010 = 110

G(5) = 5 ^ 2 = 101 ^ 010 = 111

G(6) = 6 ^ 3 = 110 ^ 011 = 101

G(7) = 7 ^ 3 = 111 ^ 011 = 100

代码:

class Solution:
    def grayCode(self, n: int) -> List[int]:
        return [i ^ i >> 1  for i in range(2 ** n)]

 

posted @ 2020-06-18 09:57  nil_f  阅读(90)  评论(0编辑  收藏  举报