LeetCode刷题实战89:格雷编码
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 格雷编码,我们先来看题面:
https://leetcode-cn.com/problems/gray-code/
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
题意
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
解题
题解
class Solution:
def grayCode(self, n: int) -> List[int]:
ret = [0]
elements = {0}
def dfs(cur):
# 遍历与cur唯一不同的二进制位
for i in range(n):
# 针对这一维做亦或,将0变1,1变0
nxt = cur ^ (1 << i)
if nxt in elements:
continue
# 记录答案,继续往下遍历
elements.add(nxt)
ret.append(nxt)
dfs(nxt)
dfs(0)
return ret
总结
上期推文:
