题目描述
链接:https://leetcode-cn.com/problems/gray-code/
思路
利用二进制,把原来的二进制反转,再高位添上1,再添到res里,因为格雷编码,所以要倒序添加。
代码
class Solution:
def grayCode(self, n):
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
参考:https://leetcode-cn.com/problems/gray-code/solution/gen-ju-ge-lei-ma-de-xing-zhi-by-powcai/
https://leetcode-cn.com/problems/gray-code/solution/gray-code-jing-xiang-fan-she-fa-by-jyd/