Kodewick
開始學 →
回溯48 / 52

回溯

第 48 課,共 52 課 · 第 9 部分 · 演算法思想 · 約 22 分鐘

回溯把所有可能有條理地一個個試:用 path.append 做選擇,遞迴往下走,再用 path.pop() 撤銷;記結果時要複製一份,走不通的路要儘早剪掉。

4 位數字的密碼鎖有 10⁴ = 10000 種開法;10 個人排隊有 10! = 3628800 種排法;20 樣東西挑一部分,有 2²⁰ = 1048576 種挑法。「把所有方案都列出來」「找出所有滿足條件的組合」這類題,沒有什麼巧辦法,只能一個個試,但要試得有條理:每一步做一個選擇,往下走;走到頭就記下來,然後撤銷這個選擇,換下一個。這就是回溯(backtracking)。它在面試裡出現得很多(全排列、子集、組合總和、N 皇后、括號生成),而且幾乎都是同一個樣子的程式碼。這一課把這個樣子寫熟,再看兩件真正決定對錯和快慢的事:記結果時要複製,走不通的路要早點剪掉。

選、往下走、撤銷

求 [1, 2, 3] 的全排列。把它想成填 3 個空:第 1 個空可以填 1、2、3;填了 1 以後,第 2 個空只能填 2 或 3……每個選擇是樹上往下的一條邊,一條從根到葉子的路就是一個排列。

[ ]
1def go():2    if len(path) == len(nums):      # 走到葉子:記下一個答案3        res.append(path[:])4        return5    for i, x in enumerate(nums):6        if used[i]:7            continue8        used[i] = True              # 選9        path.append(x)10        go()                        # 往下走11        path.pop()                  # 撤銷12        used[i] = False

[1, 2, 3] 的全排列:每一層填一位,用過的數不能再選。往下是選,退回來是撤銷,6 個葉子是 6 個排列

程式碼就是這棵樹的前序遍歷。path 是「從根走到當前結點」做過的選擇,used[i] 記第 i 個數用了沒有:

main.py
1def permute(nums):2    res, path = [], []3    used = [False] * len(nums)4 5    def go():6        if len(path) == len(nums):      # 走到葉子:記下一個答案7            res.append(path[:])8            return9        for i, x in enumerate(nums):10            if used[i]:11                continue12            used[i] = True              # 選13            path.append(x)14            go()                        # 往下走15            path.pop()                  # 撤銷16            used[i] = False17 18    go()19    return res20 21print(permute([1, 2, 3]))22print(len(permute([1, 2, 3, 4])), len(permute([1, 2, 3, 4, 5])))
輸出
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
24 120

記住這個樣子:path.append → 遞迴 → path.pop(),選了什麼,回來就撤銷什麼,三行一一對應。撤銷以後 path 和選之前一模一樣,下一輪迴圈才能乾乾淨淨地試下一個數。所有回溯題只是在換兩樣東西:什麼時候記答案,每一步能選什麼。

單選

1 2 3 的全排列按這棵決策樹的順序找(深度優先,每層從小到大選),第 4 個找到的排列是什麼?

單選

記下 1 2 3 以後,回溯下一個新走到的結點是哪個?

排順序拖動或點箭頭排順序

把「選、往下走、撤銷」這 5 行排好,讓程式印出 [1, 2, 3] 的 6 個排列。

  1. used[i] = True
  2. path.pop()
  3. used[i] = False
  4. path.append(x)
  5. go()
要顯示
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

path 要拷一份

上一關記答案寫的是 res.append(path[:]),不是 res.append(path)。少了 [:] 會怎樣?先猜:

猜輸出猜錯也沒關係

求 [1, 2] 的全排列,記答案時寫的是 res.append(path),沒有複製。印出什麼?

1res, path = [], []2used = [False, False]3 4def go():5    if len(path) == 2:6        res.append(path)7        return8    for i, x in enumerate([1, 2]):9        if not used[i]:10            used[i] = True11            path.append(x)12            go()13            path.pop()14            used[i] = False15 16go()17print(res)

這是第 1 章「名字和物件」那一課的規矩:append 進去的是引用。整個回溯從頭到尾只有一個 path 物件:

名字

path
res[0]
res[1]

物件

[]list

res.append(path) 放進去的是 path 這個物件本身;回溯結束時 path 被撤銷成空的,res 裡的每一格都指著它

path[:]、list(path)、path.copy() 都行,拷一份要 O(n),只在記答案時拷,不是每一步都拷。另一種寫法是把 path 當引數傳下去:go(path + [x]),每層都造一個新 list,不需要撤銷,也就不會犯這個錯,代價是每一步都複製。

多選可以選多個

記答案時,哪些寫法能把「當時的 path」正確地存下來?(可以選好幾個)

子集和組合

子集:[1, 2, 3] 的子集有 2³ = 8 個。為了不重複({1, 2} 和 {2, 1} 是同一個),規定只往後選:go(start) 只能從下標 start 往後挑。這樣樹上每個結點都是一個子集,不只是葉子。

[ ]

[1, 2, 3] 的子集:只往後選,所以 2 後面不會再選 1;每個結點都是一個答案,按前序記下來的順序寫在下面

組合:從 n 個裡選 k 個,就是隻要長度為 k 的子集:長度到 k 時記下並返回。

main.py
1def subsets(nums):2    res, path = [], []3 4    def go(start):5        res.append(path[:])              # 每個結點都是一個子集6        for j in range(start, len(nums)):7            path.append(nums[j])8            go(j + 1)                    # 只往後選9            path.pop()10 11    go(0)12    return res13 14def combine(nums, k):15    res, path = [], []16 17    def go(start):18        if len(path) == k:               # 選夠 k 個19            res.append(path[:])20            return21        for j in range(start, len(nums)):22            path.append(nums[j])23            go(j + 1)24            path.pop()25 26    go(0)27    return res28 29print(subsets([1, 2, 3]))30print(combine([1, 2, 3, 4], 2))31print(len(subsets(list(range(10)))), len(combine(list(range(10)), 3)))
輸出
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
1024 120

三種題的樹長得不一樣,方案數也不一樣:

題每一步能選什麼什麼時候記答案方案數
全排列沒用過的任何一個選滿 n 個n!
子集下標 start 往後的每個結點2ⁿ
組合(選 k 個)下標 start 往後的選滿 k 個C(n, k)

回溯的時間至少是方案數乘上複製一個方案的 O(n):n = 10 的全排列 362 萬個,n = 20 的子集一百多萬個。回溯只適合 n 很小的題,題目給 n ≤ 10、n ≤ 20 時就是在暗示它。

單選

5 個數的子集有幾個?從這 5 個數裡選 2 個,組合有幾種?

單選

subsets([1, 2, 3]) 按前序記下子集。第 5 個記下的是哪個?

練習 1

自己寫 combinations

補全 combine(n, k):返回從 1..n 裡選 k 個數的所有組合,每個組合從小到大,整體按字典序,結果要和 itertools.combinations 一樣(換成 list 以後)。

要顯示
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
20
True
exercise1.py
1from itertools import combinations2 3def combine(n, k):4    res, path = [], []5 6    def go(start):7        # 選夠 k 個就記下(記得複製);否則從 start 到 n 挑一個,選、往下走、撤銷8        pass9 10    go(1)11    return res12 13print(combine(4, 2))14print(len(combine(6, 3)))15print(combine(5, 3) == [list(c) for c in combinations(range(1, 6), 3)])
輸出
點「執行」或按 Ctrl+Enter

剪枝:走不通就別往下走

從 [1, 2, 3, 4] 裡挑幾個不同的數,和正好是 5。不剪枝就把 16 個子集全走一遍,再看哪些和是 5。可是先把 nums 從小到大排好,就有一個很強的判斷:當前的和加上 nums[j] 已經超過 5,後面的數只會更大,整個迴圈都可以 break。

0

[1, 2, 3, 4] 裡挑數湊 5:排好序後,一超過就 break,後面的兄弟都不用試;打叉的是試了一下就剪掉的

數一數結點:

main.py
1calls = 02 3def sum_all(nums, target):           # 不剪枝:16 個子集都走一遍4    res, path = [], []5    def go(start, total):6        global calls7        calls += 18        if total == target:9            res.append(path[:])10        for j in range(start, len(nums)):11            path.append(nums[j])12            go(j + 1, total + nums[j])13            path.pop()14    go(0, 0)15    return res16 17def sum_pruned(nums, target):        # nums 從小到大排好18    res, path = [], []19    def go(start, total):20        global calls21        calls += 122        if total == target:23            res.append(path[:])24            return                   # 再加只會更大25        for j in range(start, len(nums)):26            if total + nums[j] > target:27                break                # 剪枝:後面的數更大,更不行28            path.append(nums[j])29            go(j + 1, total + nums[j])30            path.pop()31    go(0, 0)32    return res33 34for nums, target in [([1, 2, 3, 4], 5), (list(range(1, 15)), 14)]:35    calls = 036    a = sum_all(nums, target)37    plain = calls38    calls = 039    b = sum_pruned(nums, target)40    print(f"{len(a)} 個答案,一樣嗎 {a == b};結點:不剪 {plain} 個,剪了 {calls} 個")41print(sum_pruned([1, 2, 3, 4], 5))
輸出
2 個答案,一樣嗎 True;結點:不剪 16 個,剪了 9 個
22 個答案,一樣嗎 True;結點:不剪 16384 個,剪了 110 個
[[1, 4], [2, 3]]

1 到 14 裡挑數湊 14:答案都是 22 個,不剪枝走了 16384 個結點,剪枝以後只有 110 個。剪枝不改變答案,只是不進明知走不通的路。常見的剪法:排好序後超了就 break;剩下的數不夠湊滿 k 個就停;N 皇后裡一個格子被擋住就不放(第 6 課)。

面試裡: 回溯題先畫出兩三層的樹,說清楚「每一步能選什麼、什麼時候記答案、能剪掉什麼」,再寫程式碼。最常被追問的兩處:記答案為什麼要 path[:];有重複數字([1, 1, 2])時怎麼去重:排好序後,同一層裡和前一個相同的跳過(if j > start and nums[j] == nums[j - 1]: continue)。

填空點一個填進空格,再點空格可以拿回來

nums 從小到大排好。這個比較決定什麼時候剪掉:填上空格,讓程式找出和是 5 的 [[1, 4], [2, 3]]。

1def sum_pruned(nums, target):2    res, path = [], []3 4    def go(start, total):5        if total == target:6            res.append(path[:])7            return8        for j in range(start, len(nums)):9            if total + nums[j]  target:10                break11            path.append(nums[j])12            go(j + 1, total + nums[j])13            path.pop()14 15    go(0, 0)16    return res17 18print(sum_pruned([1, 2, 3, 4], 5))
練習 2

括號生成

補全 gen(n):返回 n 對括號能組成的所有合法括號串,按字典序(( 排在 ) 前面)。剪枝:左括號用了不到 n 個才能再放 (;右括號比左括號少時才能放 )。

要顯示
['()']
['((()))', '(()())', '(())()', '()(())', '()()()']
42
exercise2.py
1def gen(n):2    res, path = [], []3 4    def go(opened, closed):5        # 長度到 2n 就記下 "".join(path)6        # 先試 "(",再試 ")",每次都是:append、往下走、pop7        pass8 9    go(0, 0)10    return res11 12print(gen(1))13print(gen(3))14print(len(gen(5)))
輸出
點「執行」或按 Ctrl+Enter

工作裡這樣寫

只是要「所有排列」「所有組合」「每一位從幾樣裡挑」,標準庫 itertools 都有,按字典序一個個給出來,不用自己寫回溯:

main.py
1from itertools import permutations, combinations, product2import math3 4print(list(permutations([1, 2, 3])))5print(list(combinations([1, 2, 3, 4], 2)))6print(list(product("ab", repeat=2)))7print(math.perm(5), math.comb(10, 3), len(list(product(range(10), repeat=4))))8 9count = 010checked = 011for r in range(15):12    for c in combinations(range(1, 15), r):13        checked += 114        if sum(c) == 14:15            count += 116print(count, "個答案,檢查了", checked, "個組合")
輸出
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
120 120 10000
22 個答案,檢查了 16384 個組合
  • permutations(xs) 全排列,permutations(xs, k) 選 k 個排;combinations(xs, k) 選 k 個不管順序;product(xs, repeat=k) 每一位都從 xs 裡挑(密碼鎖)。給出來的是元組,而且是一個個現做的,不會先佔一大塊記憶體。
  • 只要個數,不要方案:math.perm、math.comb、len 都不用列出來,直接用公式。
  • itertools 只會全部列出來,不會剪枝:湊 14 的那道題,它要檢查 16384 個組合,自己寫的回溯只走 110 個結點。有約束、能提前判斷走不通時(組合總和、N 皇后、數獨),還是手寫回溯。
猜輸出猜錯也沒關係

combinations 和 permutations 各給出幾個?

1from itertools import combinations, permutations2 3print(len(list(combinations(range(5), 2))), len(list(permutations(range(5), 2))))

小結

這一課帶走

回溯:選、往下走、撤銷

  • 一條從根到葉子的路是一個方案;程式碼是這棵樹的前序遍歷
  • path.append、遞迴、path.pop() 一一對應,撤銷後 path 和選之前一樣
  • 記答案寫 res.append(path[:]):不複製,最後全是同一個空 list
  • 排列 n!,子集 2ⁿ,組合 C(n, k):只適合 n 很小
  • 剪枝不改答案,只是不進走不通的路;沒有約束時用 itertools
1def go(start):2    res.append(path[:])3    for j in range(start, len(nums)):4        path.append(nums[j])5        go(j + 1)6        path.pop()