Leetcode刷题记录——89. 格雷编码

    技术2026-08-16  11

    class Solution: def __init__(self): self.maxa = 0 self.length = 0 self.base = [] def grayCode(self, n): self.length = 2**n self.maxa = self.length - 1 self.n = n for i in range(n): self.base.append(2**i) self.base.append(-1*2**i) print(self.base) init = [0] return self.fun(init,0) def fun(self,last_res,last_val): #print(last_res,last_val) if len(last_res) == self.length: return last_res for trial in self.base: temp_val = last_val + trial if temp_val >=0 and temp_val <= self.maxa and self.judge(temp_val,last_val) and temp_val not in last_res: last_res.append(temp_val) return self.fun(last_res,temp_val) last_res.pop(-1) def judge(self,a,b): bin_a = bin(a)[2:][::-1] bin_b = bin(b)[2:][::-1] max_length = max(len(bin_a),len(bin_b)) while len(bin_a) < max_length: bin_a += '0' while len(bin_b) < max_length: bin_b += '0' diff = 0 for i in range(max_length): if bin_a[i] != bin_b[i]: diff += 1 if diff >= 2: return False return True if diff == 1 else False
    Processed: 0.008, SQL: 9