89.格雷编码

class Solution:
    def grayCode(self, n: int) -> List[int]:
        ans = [0]
        for i in range(1, n+1):
            for j in range(len(ans)-1, -1 ,-1):
                #相当于将ans[j]往左边加了一个1
                ans.append(ans[j] | (1<<(i-1)))
        return ans


#公式法d_i = i ^ (i>>1)
class Solution:
    def grayCode(self, n: int) -> List[int]:
        total = 1 << n
        ans = [0] * total
        for i in range(total):
            ans[i] = i ^ (i>>1)
        return ans

你可能感兴趣的:(Leetcode_模拟,算法)