topic:
Topic links: https://leetcode-cn.com/problems/gray-code/
Problem-solving ideas:
N + 1 of Gray coded order, in fact, can be divided into the following two parts:
- N Gray-coded order, preceded by a 0
- Gray coded order n, in reverse order, preceded by a 1
Illustrated as follows:
n = 0 | n = 1 | n = 2 | n = 3 | n = 4 |
---|---|---|---|---|
0 | 0 | 0 0 | 0 00 | ... |
1 | 0 1 | 0 01 | ... | |
1 1 | 0 11 | ... | ||
1 0 | 0 10 | ... | ||
1 10 | ... | |||
1 11 | ... | |||
1 01 | ... | |||
1 00 | ... |
Therefore, according to Gray coding 0-order, it can be introduced at any stage of the Gray code
Code:
class Solution:
def grayCode(self, n: int) -> List[int]:
res, head = [0], 1
for i in range(n):
for j in range(len(res) - 1, -1, -1):
res.append(head + res[j])
head <<= 1
return res