您的位置:首页 > 其它

LintCode:格雷码

2016-04-24 22:21 309 查看
LintCode:格雷码

The tricky part of this question is to recognize the recursive structure here. For n = 0, sol = [0], that’s the base case. For recursive step, let’s take n = 2 and n = 3 as examples. n = 2, sol = [0, 1, 3, 2]; n = 3, sol = [0, 1, 3, 2, 6, 7, 5, 4]. Look at these two solutions, we see when n = 3, we add 4 more elements [6, 7, 5, 4] and they are just [2+4, 3+4, 1+4, 0+4]. That is sol(n+1) = sol(n) + [ reverse(sol(n)) + 2^(n) ].

class Solution:
# @param {int} n a number
# @return {int[]} Gray code
def grayCode(self, n):
# Write your code here
L = [0]
m = 0
while len(L) < pow(2, n):
L += [pow(2, m) + i for i in L[::-1]]
m += 1
return L
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: