原题
https://leetcode.cn/problems/gray-code/description/
思路
位运算
复杂度
时间:O(2n)
空间:O(2n)
Python代码
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
Go代码
func grayCode(n int) []int {
res := []int{0}
head := 1
for i := 0; i < n; i++ {
for j := len(res) - 1; j >= 0; j-- {
res = append(res, head+res[j])
}
head <<= 1
}
return res
}

663

被折叠的 条评论
为什么被折叠?



