回溯
回溯用「選、遞迴、撤銷」的模板(path.push_back、遞迴、path.pop_back)把所有可能一條條試過去,走不通就馬上退回;加上剪枝,8 皇后的 92 個解只要 2057 次呼叫。
8 × 8 的棋盤上放 8 個皇后,兩兩不能同行、同列、同斜線,有幾種放法?每行放一個、每個有 8 列可選,一共 8⁸ = 16777216 種擺法,一個個檢查當然可以。可是第 1 行放在第 0 列、第 2 行也放在第 0 列時,後面 6 行怎麼放都不行,沒必要再試。回溯就是這樣:一步一步做選擇,發現走不通就馬上退回去換一個。8 皇后這樣搜,只要 2057 次呼叫。
決策樹:一步一個選擇
把「每一步可以選什麼」畫成一棵樹:根是什麼都還沒選,每個孩子是一種選擇,從根到葉子的一條路就是一個完整的答案。這叫決策樹。回溯就是深度優先地走這棵樹:往下走是做一個選擇,走到葉子記下答案,然後撤銷最後一個選擇,退回上一層試下一個。
1void dfs(int k) { // 現在決定第 k 位2 if (k == n) { // 湊滿了:記下答案3 for (int x : path) cout << x << ' ';4 cout << '\n';5 return;6 }7 for (int i = 1; i <= n; i++) {8 if (used[i]) continue; // 用過的不能再選9 path.push_back(i); used[i] = true; // 選10 dfs(k + 1); // 遞迴11 path.pop_back(); used[i] = false; // 撤銷12 }13}
1 2 3 的全排列按這棵決策樹的順序找(深度優先,每層從小到大選),第 4 個找到的排列是什麼?
記下 1 2 3 以後,回溯下一個新走到的結點是哪個?
模板:選、遞迴、撤銷
幾乎所有回溯都長一個樣:
1void dfs(第幾步) {2 if (湊夠了) { 記下答案; return; }3 for (這一步的每個選擇) {4 if (不能選) continue;5 選; // 改狀態6 dfs(下一步);7 撤銷; // 狀態改回去,好讓下一個選擇從同樣的起點出發8 }9}
全排列:path 是一個 vector<int>,放已經選的數,used[i] 記 i 用過沒有。選就是 push_back,撤銷就是 pop_back:path 像一個堆疊,長度正好是現在的深度。
1#include <iostream>2#include <vector>3using namespace std;4 5int n = 3;6vector<int> path;7vector<bool> used(n + 1, false);8 9void dfs(int k) { // 現在決定第 k 位10 if (k == n) { // 湊滿了:記下答案11 for (int x : path) cout << x << ' ';12 cout << '\n';13 return;14 }15 for (int i = 1; i <= n; i++) {16 if (used[i]) continue; // 用過的不能再選17 path.push_back(i); used[i] = true; // 選18 dfs(k + 1); // 遞迴19 path.pop_back(); used[i] = false; // 撤銷20 }21}22 23int main() {24 dfs(0);25 return 0;26}
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
兩樣都要撤銷。少了 pop_back,path 會越來越長;少了 used[i] = false,後面的分支以為 i 還被佔著。path 和 used 用全域性變數(或者傳引用),整個搜尋只有一份,靠撤銷保持乾淨;要是按值傳 vector,每層都拷一份,就不用撤銷,但每次複製要 O(n)。
pop_back 寫了,忘了寫 used[i] = false,印出什麼?
1#include <iostream>2#include <vector>3using namespace std;4 5int n = 3;6vector<int> path;7vector<bool> used(n + 1, false);8 9void dfs(int k) {10 if (k == n) {11 for (int x : path) cout << x << ' ';12 cout << '\n';13 return;14 }15 for (int i = 1; i <= n; i++) {16 if (used[i]) continue;17 path.push_back(i); used[i] = true;18 dfs(k + 1);19 path.pop_back();20 }21}22 23int main() {24 dfs(0);25 return 0;26}
把「選、遞迴、撤銷」這 3 行排好,讓程式印出 1 2 3 的全部 6 個排列。
path.pop_back(); used[i] = false;dfs(k + 1);path.push_back(i); used[i] = true;
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
push_back(i) 放進 path,把 i 標成用過),再遞迴去決定第 k + 1 位,回來以後撤銷(pop_back(),把 i 還回去),好讓 for 迴圈的下一個 i 從同樣的狀態出發。撤銷放到遞迴前面,i 在下一層又能被選;遞迴放在最前面,i 還沒放進 path 就往下走了。子集和組合:要還是不要
全排列每一層選的是「下一位放哪個數」。子集換了一種選法:每個數只有兩個選擇,要或不要。決策樹是一棵滿二元樹,3 個數 8 個葉子,n 個數 2ⁿ 個。
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> a = {1, 2, 3};6vector<int> path;7 8void dfs(int k) { // 決定 a[k] 要不要9 if (k == (int)a.size()) {10 cout << "{ ";11 for (int x : path) cout << x << ' ';12 cout << "}\n";13 return;14 }15 path.push_back(a[k]); // 選:要 a[k]16 dfs(k + 1);17 path.pop_back(); // 撤銷18 dfs(k + 1); // 不要 a[k]19}20 21int main() {22 dfs(0);23 return 0;24}
{ 1 2 3 }
{ 1 2 }
{ 1 3 }
{ 1 }
{ 2 3 }
{ 2 }
{ 3 }
{ }
| 問題 | 每一層決定什麼 | 答案個數 | 時間 |
|---|---|---|---|
| 全排列 | 第 k 位放哪個沒用過的數 | n! | O(n · n!) |
| 子集 | 第 k 個數要不要 | 2ⁿ | O(n · 2ⁿ) |
| 組合(n 個裡選 k 個) | 下一個數從哪個開始選(只往後選) | C(n, k) | O(k · C(n, k)) |
答案本身就有這麼多,回溯沒法更快。它能省的是不會出答案的那些分支。
{1, 2, 3} 的子集,按這一關的程式(先「要」再「不要」)印出,第 3 個印出的是哪個?
5 個數的子集有幾個?從這 5 個數裡選 2 個,組合有幾種?
組合:4 個裡選 2 個
✓從 1~n 裡選 k 個,按從小到大印出每一種。為了不重複,下一個數只從 start 往後選。補全 dfs。
1 2 1 3 1 4 2 3 2 4 3 4
1#include <iostream>2#include <vector>3using namespace std;4 5int n = 4, k = 2;6vector<int> path;7 8void dfs(int start) {9 // 選夠 k 個就印出;否則 i 從 start 到 n:push_back(i),dfs(i + 1),pop_back()10}11 12int main() {13 dfs(1);14 return 0;15}
剪枝:走不通就別往下走
剪枝是在「選」之前先檢查:這一步選了以後,還有沒有可能湊出答案?不可能就 continue,整棵子樹都不用走。剪得越早,省得越多。
N 皇后:第 r 行放一個皇后,試第 0 到 n − 1 列;和前面的皇后同列、同斜線的直接跳過。同一條「\」斜線上 r − c 相同,同一條「/」斜線上 r + c 相同,用三個陣列記下哪些列、哪些斜線已經被佔,檢查只要 O(1)。
1#include <iostream>2#include <vector>3using namespace std;4 5int n, solutions;6long long calls;7vector<bool> col, d1, d2; // 列、「/」斜線 r + c、「\」斜線 r - c + n - 18 9void place(int r) {10 calls++;11 if (r == n) { solutions++; return; }12 for (int c = 0; c < n; c++) {13 if (col[c] || d1[r + c] || d2[r - c + n - 1]) continue; // 剪枝14 col[c] = d1[r + c] = d2[r - c + n - 1] = true; // 選15 place(r + 1);16 col[c] = d1[r + c] = d2[r - c + n - 1] = false; // 撤銷17 }18}19 20int main() {21 cout << "n 解 呼叫次數 不剪枝的擺法 nⁿ\n";22 for (n = 4; n <= 8; n++) {23 col.assign(n, false);24 d1.assign(2 * n - 1, false);25 d2.assign(2 * n - 1, false);26 solutions = 0;27 calls = 0;28 place(0);29 long long all = 1;30 for (int i = 0; i < n; i++) all *= n;31 cout << n << " " << solutions << " " << calls << " " << all << '\n';32 }33 return 0;34}
n 解 呼叫次數 不剪枝的擺法 nⁿ 4 2 17 256 5 10 54 3125 6 4 153 46656 7 40 552 823543 8 92 2057 16777216
8 皇后:不剪枝要檢查 16777216 種擺法,剪枝以後整棵樹只有 2057 個結點。回溯的最壞情況仍然是指數級(N 皇后大約 O(n!)),剪枝改變不了這一點,但能把實際搜尋的量壓低好幾個數量級。
考試裡: 408 很少直接考回溯的程式碼,常考的是 N 皇后的解法過程、「n 個數的全排列有幾個」「子集有幾個」。面試裡全排列、子集、組合、組合總和、N 皇后幾乎都是這一個模板:畫出決策樹,想清楚每層選什麼、什麼時候湊夠、哪些能剪。
4 皇后一共 2 個解。第一個解每行的列是 1 3 0 2,接著回溯找到的第二個解是什麼?
0 2 1 3 和 3 0 2 1 裡都有兩個皇后在同一條斜線上。「/」斜線上的格子 r + c 相同,「\」斜線上 r − c 相同(加 n − 1 免得下標變負)。補上 s,讓程式印出 4 到 8 皇后各有幾個解。
1#include <iostream>2#include <vector>3using namespace std;4 5int n, solutions;6vector<bool> col, d1, d2;7 8void place(int r) {9 if (r == n) { solutions++; return; }10 for (int c = 0; c < n; c++) {11 int s = , t = r - c + n - 1;12 if (col[c] || d1[s] || d2[t]) continue;13 col[c] = d1[s] = d2[t] = true;14 place(r + 1);15 col[c] = d1[s] = d2[t] = false;16 }17}18 19int main() {20 for (n = 4; n <= 8; n++) {21 col.assign(n, false);22 d1.assign(2 * n - 1, false);23 d2.assign(2 * n - 1, false);24 solutions = 0;25 place(0);26 cout << solutions << " ";27 }28 cout << "\n";29 return 0;30}
r - c 會算出負的下標;選 c 就和列重複了,擋不住斜線。組合總和(帶剪枝)
✓從 2、3、5 裡選數(同一個數可以選多次),加起來等於 8,印出每一種(數從小到大)。陣列已經排好序:加上 a[i] 就超過 8 時,後面的更大,直接 break。
2 2 2 2 2 3 3 3 5
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> a = {2, 3, 5};6int target = 8;7vector<int> path;8 9void dfs(int start, int sum) {10 // sum == target 就印出;否則 i 從 start 開始:sum + a[i] > target 就 break;11 // push_back(a[i]),dfs(i, sum + a[i])(還能再選自己),pop_back()12}13 14int main() {15 dfs(0, 0);16 return 0;17}
用 STL 寫
回溯的「選、遞迴、撤銷」STL 替不了你,但有兩樣常用的幫手:
next_permutation(b, e)(<algorithm>):把一段改成字典序裡的下一個排列,已經是最後一個(從大到小)時改回最小的並返回false。從排好序的開始,do { … } while (next_permutation(…));就按順序走遍所有排列。有重複的數時,它只給不同的排列,不用自己去重。bitset<N>(<bitset>):N 個開關,b[i]、b.set(i)、b.reset(i)、b.test(i)、b.count()都是 O(1)(count是 O(N / 64))。拿來當used、N 皇后的列和斜線,比vector<bool>更省;一個整數mask也可以當 0~2ⁿ − 1 的「子集編號」,第 i 位是 1 就是要 a[i]。
1#include <iostream>2#include <vector>3#include <algorithm>4#include <bitset>5using namespace std;6 7int main() {8 vector<int> p = {1, 2, 3}; // 先排好序9 int count = 0;10 do {11 for (int x : p) cout << x << ' ';12 cout << '\n';13 count++;14 } while (next_permutation(p.begin(), p.end()));15 cout << "一共 " << count << " 個\n";16 17 vector<int> q = {1, 1, 2}; // 有重複的數18 count = 0;19 do count++; while (next_permutation(q.begin(), q.end()));20 cout << "1 1 2 不同的排列:" << count << " 個\n";21 22 vector<int> a = {1, 2, 3};23 for (int mask = 0; mask < (1 << 3); mask++) { // 子集:mask 的第 i 位管 a[i]24 bitset<3> b(mask);25 cout << b << " → { ";26 for (int i = 0; i < 3; i++)27 if (b.test(i)) cout << a[i] << ' ';28 cout << "}\n";29 }30 return 0;31}
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
一共 6 個
1 1 2 不同的排列:3 個
000 → { }
001 → { 1 }
010 → { 2 }
011 → { 1 2 }
100 → { 3 }
101 → { 1 3 }
110 → { 2 3 }
111 → { 1 2 3 }
cout << b 從最高位往低位印出,所以 001 表示第 0 位是 1,也就是隻要 a[0]。
裡面是什麼:next_permutation 從右往左找第一個「比右邊小」的位置 i,再從右邊找一個剛好比它大的數和它交換,最後把 i 後面那段倒過來。每次最壞 O(n),走遍 n! 個排列平均每次 O(1)。bitset<N> 把 N 位放在幾個 64 位整數裡,N 必須是編譯時就知道的常數。
| 寫法 | 做什麼 | 代價 |
|---|---|---|
path.push_back(x) / path.pop_back() | 選 / 撤銷 | O(1)(均攤) |
next_permutation(b, e) | 下一個字典序排列,最後一個時返回 false | 最壞 O(n),平均 O(1) |
bitset<N> b; b.set(i); b.reset(i); b.test(i) | 用過沒有 | O(1) |
for (mask = 0; mask < (1 << n); mask++) | 不遞迴地走遍 2ⁿ 個子集 | O(n · 2ⁿ) |
面試裡: 「全排列」可以直接 next_permutation,但面試官多半要你寫回溯;「全排列 II(有重複)」先 sort,同一層裡跳過和前一個相同、而前一個沒被用的數:if (i > 0 && a[i] == a[i - 1] && !used[i - 1]) continue;。被問複雜度,說「答案個數 × 每個答案的長度」,再說剪枝能省多少。
這次沒有先排序,從 2 1 3 開始。程式輸出幾?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> p = {2, 1, 3};8 int count = 0;9 do count++; while (next_permutation(p.begin(), p.end()));10 cout << count << "\n";11 return 0;12}
next_permutation 只往字典序後面走:2 1 3、2 3 1、3 1 2、3 2 1,到了最大的 3 2 1 就返回 false,一共 4 個。排在 2 1 3 前面的 1 2 3、1 3 2 根本沒走到。所以要列出全部排列,先 sort。小結
回溯:一條路一條路試,走不通就退回來
- 決策樹:每層一個選擇,根到葉子是一個答案
- 模板:湊夠就記下;否則對每個選擇:選、遞迴、撤銷
- path.push_back 是選,path.pop_back 是撤銷;忘了撤銷,後面的分支就看到錯的狀態
- 剪枝:選之前先檢查,不可能的整棵子樹都不走
- next_permutation 按字典序走遍排列,bitset 記用過的
1for (int i = 0; i < n; i++) {2 if (used[i]) continue;3 path.push_back(a[i]); used[i] = true;4 dfs(k + 1);5 path.pop_back(); used[i] = false;6}