Problem :

https://leetcode.com/problems/gray-code/


My Solution :

class Solution:
def grayCode(self, n):
def dfs():
if len(path) == 2**n:
return path[:]
num = path[-1]
visited[num] = 1
for i in range(n):
cand = num ^ 1 << i
if not visited[cand]:
path.append(cand)
ret = dfs()
if ret:
return ret
path.pop()
visited[num] = 0

path = [0]
visited = [0]*(2**n)
return dfs()