回溯
回溯把所有可能有條理地一個個試:用 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
程式碼就是這棵樹的前序遍歷。path 是「從根走到當前結點」做過的選擇,used[i] 記第 i 個數用了沒有:
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 個排列。
used[i] = Truepath.pop()used[i] = Falsepath.append(x)go()
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
go() 前面,path 還沒放進 x 就往下走,結果就亂了。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)
res.append(path) 放進去的是 path 這個 list 物件本身,不是它當時的樣子。之後 path 一直被 pop、append,最後全部撤銷變回空的;res 裡的兩格都指著它,所以打印出兩個空 list。[[2, 1], [2, 1]] 是「最後一次的樣子」,可最後還有撤銷。這是第 1 章「名字和物件」那一課的規矩:append 進去的是引用。整個回溯從頭到尾只有一個 path 物件:
名字
pathres[0]res[1]物件
path[:]、list(path)、path.copy() 都行,拷一份要 O(n),只在記答案時拷,不是每一步都拷。另一種寫法是把 path 當引數傳下去:go(path + [x]),每層都造一個新 list,不需要撤銷,也就不會犯這個錯,代價是每一步都複製。
記答案時,哪些寫法能把「當時的 path」正確地存下來?(可以選好幾個)
path[:]、list(path)、path.copy() 都會造一個新 list,內容是當時的樣子,以後 path 再變也不影響它。res.append(path) 放進去的是 path 這個物件本身,回溯結束時它被撤銷成空的。子集和組合
子集:[1, 2, 3] 的子集有 2³ = 8 個。為了不重複({1, 2} 和 {2, 1} 是同一個),規定只往後選:go(start) 只能從下標 start 往後挑。這樣樹上每個結點都是一個子集,不只是葉子。
組合:從 n 個裡選 k 個,就是隻要長度為 k 的子集:長度到 k 時記下並返回。
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 個記下的是哪個?
自己寫 combinations
✓補全 combine(n, k):返回從 1..n 裡選 k 個數的所有組合,每個組合從小到大,整體按字典序,結果要和 itertools.combinations 一樣(換成 list 以後)。
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 20 True
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)])
剪枝:走不通就別往下走
從 [1, 2, 3, 4] 裡挑幾個不同的數,和正好是 5。不剪枝就把 16 個子集全走一遍,再看哪些和是 5。可是先把 nums 從小到大排好,就有一個很強的判斷:當前的和加上 nums[j] 已經超過 5,後面的數只會更大,整個迴圈都可以 break。
數一數結點:
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))
>=,正好等於 5 的那一步也被剪掉,一個答案都找不到;< 和 == 在還能湊的時候就 break 了。括號生成
✓補全 gen(n):返回 n 對括號能組成的所有合法括號串,按字典序(( 排在 ) 前面)。剪枝:左括號用了不到 n 個才能再放 (;右括號比左括號少時才能放 )。
['()'] ['((()))', '(()())', '(())()', '()(())', '()()()'] 42
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)))
工作裡這樣寫
只是要「所有排列」「所有組合」「每一位從幾樣裡挑」,標準庫 itertools 都有,按字典序一個個給出來,不用自己寫回溯:
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))))
math.comb(5, 2) 和 math.perm(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()