-
Notifications
You must be signed in to change notification settings - Fork 43
/
gray-code.py
263 lines (224 loc) · 7.9 KB
/
gray-code.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""
89. Gray Code
Medium
An n-bit gray code sequence is a sequence of 2n integers where:
Every integer is in the inclusive range [0, 2n - 1],
The first integer is 0,
An integer appears no more than once in the sequence,
The binary representation of every pair of adjacent integers differs by exactly one bit, and
The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.
Example 1:
Input: n = 2
Output: [0,1,3,2]
Explanation:
The binary representation of [0,1,3,2] is [00,01,11,10].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
Example 2:
Input: n = 1
Output: [0,1]
Constraints:
1 <= n <= 16
"""
# V0
# IDEA : bit op
# https://blog.csdn.net/qqxx6661/article/details/78371259
# DEMO
# i = 0 bin(i) = 0b0 bin(i >> 1) = 0b0 bin(i >> 1) ^ i = 0b0
# i = 1 bin(i) = 0b1 bin(i >> 1) = 0b0 bin(i >> 1) ^ i = 0b1
# i = 2 bin(i) = 0b10 bin(i >> 1) = 0b1 bin(i >> 1) ^ i = 0b11
# i = 3 bin(i) = 0b11 bin(i >> 1) = 0b1 bin(i >> 1) ^ i = 0b10
# i = 4 bin(i) = 0b100 bin(i >> 1) = 0b10 bin(i >> 1) ^ i = 0b110
# i = 5 bin(i) = 0b101 bin(i >> 1) = 0b10 bin(i >> 1) ^ i = 0b111
# i = 6 bin(i) = 0b110 bin(i >> 1) = 0b11 bin(i >> 1) ^ i = 0b101
# i = 7 bin(i) = 0b111 bin(i >> 1) = 0b11 bin(i >> 1) ^ i = 0b100
# i = 8 bin(i) = 0b1000 bin(i >> 1) = 0b100 bin(i >> 1) ^ i = 0b1100
# i = 9 bin(i) = 0b1001 bin(i >> 1) = 0b100 bin(i >> 1) ^ i = 0b1101
# i = 10 bin(i) = 0b1010 bin(i >> 1) = 0b101 bin(i >> 1) ^ i = 0b1111
# i = 11 bin(i) = 0b1011 bin(i >> 1) = 0b101 bin(i >> 1) ^ i = 0b1110
# i = 12 bin(i) = 0b1100 bin(i >> 1) = 0b110 bin(i >> 1) ^ i = 0b1010
# i = 13 bin(i) = 0b1101 bin(i >> 1) = 0b110 bin(i >> 1) ^ i = 0b1011
# i = 14 bin(i) = 0b1110 bin(i >> 1) = 0b111 bin(i >> 1) ^ i = 0b1001
# i = 15 bin(i) = 0b1111 bin(i >> 1) = 0b111 bin(i >> 1) ^ i = 0b1000
class Solution(object):
def grayCode(self, n):
res = []
size = 2**n
for i in range(size):
print ("i = " + str(i) + " bin(i) = " + str(bin(i)) + " bin(i >> 1) = " + str(bin(i >> 1)) + " bin(i >> 1) ^ i = " + str( bin((i >> 1) ^ i) ) )
"""
NOTE :
step 1) we move 1 digit right in every iteration (i >> 1), for keep adding space
step 2) we do (i >> 1) ^ i. for getting "inverse" binary code with i
step 3) append and return the result
"""
res.append((i >> 1) ^ i)
return res
# V0
# IDEA : RECURSION & grayCode property
class Solution(object):
def grayCode(self, n):
def help(n):
if n == 0:
return ['0']
elif n == 1:
return ['0', '1']
prev = help(n-1)
return ['0' + x for x in prev] + ['1' + x for x in prev[::-1]]
return [int(x, 2) for x in help(n)]
# V0
# IDEA : RECURSION & grayCode property
# -> binary representation of grayCode(n) can be composed of the solution of grayCode(n - 1) padded with zeros, concatenated with the reversed grayCode(n - 1) padded with ones.
# -> example : the binary representation of grayCode(2) is [00, 01, 11, 10]
# -> the first half of which can be thought of as 0 followed by [0, 1] (the binary representation of grayCode(1)),
# -> and the second half of which can be thought of as 1 followed by [1, 0] (the reversed binary representation of grayCode(1)).
# -> (0 and 1 are treated as a special case)
#
# How does int(x[,base]) work?
# -> https://stackoverflow.com/questions/33664451/how-does-intx-base-work
# -> int(string, base) accepts an arbitrary base. You are probably familiar with binary and hexadecimal, and perhaps octal; these are just ways of noting an integer number in different bases:
# exmaple :
# In [76]: int('10',2) # transform '10' to a 2 bases int
# Out[76]: 2
#
# In [77]: int('11',2) # transform '11' to a 2 bases int
# Out[77]: 3
#
# In [78]: int('100',2) # transform '100' to a 2 bases int
# Out[78]: 4
class Solution:
def grayCode(self, n):
def help(n):
if n == 0:
return ['0']
if n == 1:
return ['0', '1']
prev = help(n - 1)
return ['0' + code for code in prev] + ['1' + code for code in reversed(prev)]
return [int(code, 2) for code in help(n)]
# V1
# https://leetcode.com/problems/gray-code/discuss/312866/40-ms-recursive-Python-solution
class Solution:
def grayCode(self, n):
def help(n):
if n == 0:
return ['0']
if n == 1:
return ['0', '1']
prev = help(n - 1)
return ['0' + code for code in prev] + ['1' + code for code in reversed(prev)]
return [int(code, 2) for code in help(n)]
# V1'
# https://ithelp.ithome.com.tw/articles/10213273
# DEMO
# In [23]: add=1
# In [24]: add<<=1
# In [25]: add
# Out[25]: 2
# In [26]: add<<=1
# In [27]: add
# Out[27]: 4
# In [28]: add<<=1
# In [29]: add
# Out[29]: 8
# In [30]: add<<=1
# In [31]: add
# Out[31]: 16
# In [32]: add<<=1
# In [33]: add
# Out[33]: 32
class Solution:
def grayCode(self, n):
res = [0]
add = 1
for _ in range(n):
for i in range(add):
res.append(res[add - 1 - i] + add);
add <<= 1
return res
### Test case : dev
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/80664204
# IDEA : ITERATION
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
grays = dict()
grays[0] = ['0']
grays[1] = ['0', '1']
for i in range(2, n + 1):
n_gray = []
for pre in grays[i - 1]:
n_gray.append('0' + pre)
for pre in grays[i - 1][::-1]:
n_gray.append('1' + pre)
grays[i] = n_gray
return map(lambda x: int(x, 2), grays[n])
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/80664204
# IDEA : RECURSION
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
return map(lambda x: int(x, 2), self.bit_gray(n))
def bit_gray(self, n):
ans = None
if n == 0:
ans = ['0']
elif n == 1:
ans = ['0', '1']
else:
pre_gray = self.bit_gray(n - 1)
ans = ['0' + x for x in pre_gray] + ['1' + x for x in pre_gray[::-1]]
return ans
# V1''
# https://blog.csdn.net/qqxx6661/article/details/78371259
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = []
#size = 1 << n # if n=4, left move 4 digits, from 1 to 10000, which is 16
size = 2**n # above is OK as well
for i in range(size):
res.append((i >> 1) ^ i)
return res
# V2
# Time: O(2^n)
# Space: O(1)
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = [0]
for i in range(n):
for n in reversed(result):
result.append(1 << i | n)
return result
# Proof of closed form formula could be found here:
# http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code
class Solution2(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
return [i >> 1 ^ i for i in range(1 << n)]