边工作边刷题:70天一遍leetcode: day 21-1

Gray Code

要点:这题有两个记忆点:

  • 结果可以append到同一个结果list上,只需要在loop确定循环变量的范围
  • 迭代的过程是高位增加一位,为什么初始情况一样?其实高位增加1位即对同位的0+1,开始的时候是[0]就等同于没有低位。
class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        res = [0]
        for i in range(n):
            n = len(res)
            for k in range(n-1, -1, -1):
                res.append(int(1<<i) + res[k])
        
        return res

posted @ 2016-04-28 10:09  absolute100  阅读(90)  评论(0编辑  收藏  举报