Backtracking
Backtracking tries every possibility path by path with a choose, explore, unchoose template (path.push_back, recurse, path.pop_back), stepping back as soon as a path can't work; with pruning, 8 queens finds all 92 solutions in 2057 calls.
Put 8 queens on an 8 × 8 board, no two in the same row, column or diagonal: how many ways are there? One queen per row, 8 columns to choose for each: 8⁸ = 16777216 placements, and you could check them one by one. But once the queen in row 1 is in column 0 and the one in row 2 is in column 0 too, nothing in the other 6 rows can save it, so there's no point trying. That's backtracking: make choices one step at a time, and the moment a path can't work, step back and change the choice. Searching 8 queens this way takes 2057 calls.
The decision tree: one choice per step
Draw "what can be chosen at each step" as a tree: the root is nothing chosen yet, each child is one choice, and a path from the root to a leaf is a whole answer. This is the decision tree. Backtracking walks this tree depth first: going down makes a choice, at a leaf the answer is recorded, then the last choice is undone and it goes back up a level to try the next one.
1void dfs(int k) { // now deciding place k2 if (k == n) { // all places full: record the answer3 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; // a used number can't be chosen again9 path.push_back(i); used[i] = true; // choose10 dfs(k + 1); // explore11 path.pop_back(); used[i] = false; // unchoose12 }13}
Finding the permutations of 1 2 3 in the order of this decision tree (depth first, smaller numbers first at each level), which permutation is found 4th?
After recording 1 2 3, which is the next new node the backtracking reaches?
The template: choose, explore, unchoose
Nearly every backtracking search looks the same:
1void dfs(step) {2 if (complete) { record the answer; return; }3 for (each choice at this step) {4 if (not allowed) continue;5 choose; // change the state6 dfs(next step);7 unchoose; // change it back, so the next choice starts from the same place8 }9}
Permutations: path is a vector<int> holding the numbers chosen so far, and used[i] says whether i is taken. Choosing is push_back, unchoosing is pop_back: path works like a stack, and its length is exactly the current depth.
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) { // now deciding place k10 if (k == n) { // all places full: record the answer11 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; // a used number can't be chosen again17 path.push_back(i); used[i] = true; // choose18 dfs(k + 1); // explore19 path.pop_back(); used[i] = false; // unchoose20 }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
Both need undoing. Without the pop_back, path keeps growing; without used[i] = false, the later branches think i is still taken. path and used are globals (or passed by reference), so there is one copy for the whole search, kept clean by unchoosing; pass the vector by value instead and every level gets its own copy, with nothing to undo, but each copy costs O(n).
The pop_back is there, but used[i] = false is missing. What does it print?
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}
Put the 3 lines "choose, explore, unchoose" in order so the program prints all 6 permutations of 1 2 3.
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) onto path and mark i as used), then recurse to decide place k + 1, and when it comes back, unchoose (pop_back() and give i back) so the loop's next i starts from the same state. With the undo before the recursion, i could be chosen again one level down; with the recursion first, it goes down before i is on the path.Subsets and combinations: in or out
In a permutation, each level picks which number comes next. Subsets choose another way: each number has just two choices, in or out. The decision tree is a full binary tree: 8 leaves for 3 numbers, 2ⁿ for n.
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> a = {1, 2, 3};6vector<int> path;7 8void dfs(int k) { // decide whether a[k] is in9 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]); // choose: a[k] is in16 dfs(k + 1);17 path.pop_back(); // unchoose18 dfs(k + 1); // a[k] is out19}20 21int main() {22 dfs(0);23 return 0;24}
{ 1 2 3 }
{ 1 2 }
{ 1 3 }
{ 1 }
{ 2 3 }
{ 2 }
{ 3 }
{ }
| Problem | What each level decides | Answers | Time |
|---|---|---|---|
| Permutations | Which unused number goes in place k | n! | O(n · n!) |
| Subsets | Whether the k-th number is in | 2ⁿ | O(n · 2ⁿ) |
| Combinations (k of n) | Where the next number starts (only forward) | C(n, k) | O(k · C(n, k)) |
There are that many answers, so backtracking can't be faster than that. What it can save is the branches that will never give an answer.
Printing the subsets of {1, 2, 3} with this step's program ("in" first, then "out"), which one is printed 3rd?
How many subsets do 5 numbers have? And how many ways are there to pick 2 of them?
Combinations: 2 out of 4
✓Choose k numbers from 1 to n and print every way, smallest first. To avoid repeats, the next number is only chosen from start onward. Complete 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 chosen: print them; otherwise i from start to n: push_back(i), dfs(i + 1), pop_back()10}11 12int main() {13 dfs(1);14 return 0;15}
Pruning: don't go down a path that can't work
Pruning checks before choosing: with this choice made, can an answer still come out? If not, continue, and that whole subtree is never walked. The earlier you prune, the more you save.
N-queens: row r gets one queen, trying columns 0 to n − 1; any column in the same column or diagonal as an earlier queen is skipped. On one "\" diagonal r − c is the same, on one "/" diagonal r + c is the same, so three arrays record which columns and diagonals are taken, and each check is O(1).
1#include <iostream>2#include <vector>3using namespace std;4 5int n, solutions;6long long calls;7vector<bool> col, d1, d2; // columns, "/" diagonals r + c, "\" diagonals 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; // prune14 col[c] = d1[r + c] = d2[r - c + n - 1] = true; // choose15 place(r + 1);16 col[c] = d1[r + c] = d2[r - c + n - 1] = false; // unchoose17 }18}19 20int main() {21 cout << "n solutions calls placements without pruning 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 solutions calls placements without pruning nⁿ 4 2 17 256 5 10 54 3125 6 4 153 46656 7 40 552 823543 8 92 2057 16777216
8 queens: without pruning there are 16777216 placements to check; with it, the whole tree has only 2057 nodes. Backtracking's worst case is still exponential (N-queens is about O(n!)), and pruning can't change that, but it cuts the search actually done by several orders of magnitude.
In exams: exam papers seldom ask for backtracking code itself; they ask you to trace N-queens, or "how many permutations do n numbers have", "how many subsets". In interviews, permutations, subsets, combinations, combination sum and N-queens are nearly all this one template: draw the decision tree, then be clear what each level chooses, when it's complete, and what can be pruned.
4 queens has 2 answers. The first puts the queens in columns 1 3 0 2, row by row. What is the second answer the backtracking finds?
0 2 1 3 and 3 0 2 1 both put two queens on the same diagonal.Squares on a "/" diagonal share r + c; squares on a "\" diagonal share r − c (plus n − 1 so the index is never negative). Fill in s so the program prints how many answers 4 to 8 queens have.
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 gives negative indexes, and c just repeats the column check and lets diagonals through.Combination sum (with pruning)
✓Choose numbers from 2, 3 and 5 (the same one may be chosen again) adding up to 8, and print every way (numbers smallest first). The array is sorted: once adding a[i] goes over 8, the later ones are bigger, so just 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: print; otherwise i from start: break if sum + a[i] > target;11 // push_back(a[i]), dfs(i, sum + a[i]) (it can be chosen again), pop_back()12}13 14int main() {15 dfs(0, 0);16 return 0;17}
With the STL
The STL can't do the choose, explore, unchoose for you, but two helpers come up a lot:
next_permutation(b, e)(<algorithm>): turns a range into the next permutation in dictionary order; when it is already the last one (largest first), it turns it back into the smallest and returnsfalse. Start sorted, anddo { … } while (next_permutation(…));walks every permutation in order. With repeated numbers it gives only the distinct permutations, with no removing of duplicates on your part.bitset<N>(<bitset>): N switches;b[i],b.set(i),b.reset(i),b.test(i)are O(1) (b.count()is O(N / 64)). Use it forused, or for the columns and diagonals of N-queens, more compactly thanvector<bool>; a plain integermaskcan also serve as a "subset number" from 0 to 2ⁿ − 1, where bit i set means a[i] is in.
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}; // sorted first9 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 << " in all\n";16 17 vector<int> q = {1, 1, 2}; // with a repeated number18 count = 0;19 do count++; while (next_permutation(q.begin(), q.end()));20 cout << "distinct permutations of 1 1 2: " << count << '\n';21 22 vector<int> a = {1, 2, 3};23 for (int mask = 0; mask < (1 << 3); mask++) { // subsets: bit i of mask is for 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 in all
distinct permutations of 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 prints from the highest bit down, so 001 means bit 0 is set: only a[0] is in.
What's inside: next_permutation looks from the right for the first place i that is "smaller than its right neighbour", swaps it with the number on its right that is just bigger than it, then reverses everything after i. Each call is O(n) at worst, and O(1) on average over all n! permutations. bitset<N> packs its N bits into a few 64-bit integers, and N has to be a constant known when compiling.
| Code | What it does | Cost |
|---|---|---|
path.push_back(x) / path.pop_back() | Choose / unchoose | O(1) (amortised) |
next_permutation(b, e) | The next permutation in dictionary order, false after the last | O(n) at worst, O(1) on average |
bitset<N> b; b.set(i); b.reset(i); b.test(i) | Is it used? | O(1) |
for (mask = 0; mask < (1 << n); mask++) | All 2ⁿ subsets without recursion | O(n · 2ⁿ) |
In interviews: "permutations" can be just next_permutation, but the interviewer usually wants the backtracking; for "permutations II (with repeats)", sort first, then within one level skip a number equal to the one before it when the one before isn't in use: if (i > 0 && a[i] == a[i - 1] && !used[i - 1]) continue;. Asked for the cost, say "number of answers × length of each", then how much pruning saves.
This time there is no sort first: it starts from 2 1 3. What does the program print?
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 only moves forward in dictionary order: 2 1 3, 2 3 1, 3 1 2, 3 2 1, and at the largest, 3 2 1, it returns false. That's 4. The ones before 2 1 3, namely 1 2 3 and 1 3 2, are never reached. To list every permutation, sort first.Summary
Backtracking: one path at a time, back up when it goes nowhere
- The decision tree: one choice per level, root to leaf is one answer
- The template: complete, record it; otherwise for each choice: choose, explore, unchoose
- path.push_back chooses, path.pop_back unchooses; forget to unchoose and the later branches see the wrong state
- Prune: check before choosing, and skip whole subtrees that can't work
- next_permutation walks permutations in dictionary order, bitset records what's used
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}