?LeetCode刷題實(shí)戰(zhàn)89:格雷編碼
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號后續(xù)每天帶大家做一道算法題,題目就從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]?也是一個(gè)有效的格雷編碼序列。
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唯一不同的二進(jìn)制位
????????????for?i in?range(n):
????????????????# 針對這一維做亦或,將0變1,1變0
????????????????nxt = cur ^ (1?<< i)
????????????????if?nxt in?elements:
????????????????????continue
????????????????# 記錄答案,繼續(xù)往下遍歷
????????????????elements.add(nxt)
????????????????ret.append(nxt)
????????????????dfs(nxt)
????????dfs(0)
????????return?ret
總結(jié)
上期推文:
