1. 程式人生 > 實用技巧 >格雷碼

格雷碼

在經典漢諾塔問題中,有 3 根柱子及 N 個不同大小的穿孔圓盤,盤子可以滑入任意一根柱子。一開始,所有盤子自上而下按升序依次套在第一根柱子上(即每一個盤子只能放在更大的盤子上面)。移動圓盤時受到以下限制:
(1) 每次只能移動一個盤子;
(2) 盤子只能從柱子頂端滑出移到下一根柱子;
(3) 盤子只能疊在比它大的盤子上。

請編寫程式,用棧將所有盤子從第一根柱子移到最後一根柱子。

你需要原地修改棧。

示例1:

輸入:A = [2, 1, 0], B = [], C = []
輸出:C = [2, 1, 0]
示例2:

輸入:A = [1, 0], B = [], C = []
輸出:C = [1, 0]
提示:

A中盤子的數目不大於14個。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/hanota-lcci

class Solution:
    def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
        """
        Do not return anything, modify C in-place instead.
        """
        self.move(len(A),A,B,C)
        return C
    
def move(self,n,A,B,C): if n == 1: C.append(A.pop()) else: self.move(n-1,A,C,B) C.append(A.pop()) self.move(n-1,B,A,C)