回溯
回溯把所有可能有条理地一个个试:用 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()