题目:
题目链接: https://leetcode-cn.com/problems/gray-code/
解题思路:
对n + 1阶的格雷编码,其实可以分成下面两部分:
- n阶的格雷编码,前面加一个0
- n阶的格雷编码,按照倒序,前面加一个1
图示如下:
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 | ... |
所以,根据0阶的格雷编码,可以推出任意阶的格雷编码
代码实现:
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