-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraycode.py
More file actions
27 lines (25 loc) · 735 Bytes
/
Copy pathgraycode.py
File metadata and controls
27 lines (25 loc) · 735 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n==0:
return [0]
s=''
for i in range(n):
s+='0'
d={}
ans=[]
return self.helper(s,d,ans)
def helper(self,num,dic,ans):
if dic.get(num)==None:
ans.append(int(num,2))
dic[num]=True
num=list(num)
for i in range(len(num)-1,-1,-1):
if num[i]=='0':
ans=self.helper(''.join(num[0:i]+['1']+num[i+1:]),dic,ans)
else:
ans=self.helper(''.join(num[0:i]+['0']+num[i+1:]),dic,ans)
return ans