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