Backtracking: choose, explore, undo
1 Every order of three books
Three books, numbered 1, 2 and 3, go on a shelf with three slots. We want every order they can stand in.
We put a book in the first slot, one of the two left in the second, and the last one in the third. The shelf is full, so we write the order down. Then we take the last book off and look for another book for that slot. When a slot has nothing left to try, we take one more book off and go back a slot.
This walk is backtracking. We make a choice, explore everything that can follow it, then undo the choice and try the next one.
The pick-or-skip lesson walked the same way with two choices per element, in or out. Here a slot has as many choices as there are books left, so the two calls become a loop.
In a tree drawing, each level is a slot, and each branch is the book put in it. Every path from the top to the bottom is one order:
The tree branches 3 ways at the top, 2 ways under that and 1 way under that, so it has 3 × 2 × 1 = 6 orders. This is the decision tree. Backtracking walks it from left to right, one path at a time.
2 Choose, explore, undo
Every problem in this section follows one template. The state is what we have built so far: our shelf.
backtrack(state)
if state is complete
record a copy of state
return
for each choice
if the choice is allowed
choose: apply it to state
explore: backtrack(state)
undo: take it back off state
For the books, the state has two parts:
currentholds the books on the shelf, in order. Choose adds a book at the end, and undo removes it.usedsays, for each index i, whethernums[i]is on the shelf. A book on the shelf is not allowed in another slot.
The state is complete when current holds all n books. The steps below walk the left part of the tree for nums = [1, 2, 3]:
Each undo puts the state back exactly as it was before the choice. So when a call returns, the loop above it finds the shelf as it left it, and moves on to its next book. The whole run records [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1], in that order.
3 The code: permute
Permutations asks for exactly this: every order of nums, where all the values are different. Each part of the template becomes a line or two of code.
On [1, 2, 3] it returns the six orders in the order the steps found them. On [7] it returns [[7]].
Every call shares one current and one used. A fresh list for each call would also work, but it copies up to n values at every node of the tree. Sharing is cheaper, and it gives us one rule: undo must reverse choose exactly. The code adds a book and marks it, so it must remove the book and clear the mark.
Recording is the one place we copy. current keeps changing after we record it, and at the end of the run it is empty again. A stored list without a copy would show that final state.
C++
The copy is automatic. push_back(current) copies the vector into result, so later changes to current do not reach it.
Copy with new ArrayList<>(current). result.add(current) stores the same list six times, and the result is six empty lists.
Copy with current.copy(). result.append(current) stores the same list six times, and the result is six empty lists.
Copy with [...current]. result.push(current) stores the same array six times, and the result is six empty arrays.
Copy with make and copy. Appending current itself stores slices that share one backing array. On [1, 2, 3] the result is six copies of [3 2 1].
Copy with current.clone(). Pushing current itself would move it into result, so the compiler stops this mistake.
Copy with new List<int>(current). result.Add(current) stores the same list six times, and the result is six empty lists.
4 Combinations: a start index
Combinations asks for every group of k numbers from 1 to n. A group has no order, so [1, 2] and [2, 1] are the same group. The permutation loop would find both, because every slot starts again from the first number.
The fix is a start index. Each call's loop tries only the numbers from start onwards, and after we choose i, the next slot starts at i + 1:
backtrack(start)
if current has k numbers
record a copy of current
return
for i from start to n
add i to current
backtrack(i + 1)
remove i from current
Now a number can only follow a smaller one, so each group comes out once, in increasing order. Nothing before start can be chosen, so the used array goes away.
The drawing leaves out the branch for 4 at the top. Nothing comes after 4, so that branch records nothing.
Two more problems in this section change one line each:
- Subsets. Every node of the tree is a subset, not only the full ones. So each call records a copy of
currentfirst, then runs its loop. The root records the empty subset. - Combination Sum. A number can be used again, so after choosing i, the next slot starts at i, not i + 1. We record when the sum reaches the target, and a choice is allowed only while the sum stays within it. With [2, 3, 5] and target 8, that finds [2, 2, 2, 2], [2, 3, 3] and [3, 5].
5 Duplicate values in the input
Subsets II gives an array that can hold the same value twice, and wants each subset once. Take nums = [1, 2, 2]. The subset loop records [1, 2] twice and [2] twice: once with the 2 at index 1, once with the 2 at index 2.
The fix has two parts:
- Sort
nums, so equal values sit next to each other. - In the loop, skip i when
i > startandnums[i] == nums[i - 1].
The rule works on one slot. One call's loop tries each choice in the same slot. After the first 2 has had that slot, the second 2 would grow the same branch again, so we skip it. A deeper call fills the next slot, and there a 2 after a 2 is new: it makes [2, 2].
The i > start part lets [2, 2] through. In the second call, i = 2 equals start, so the rule does not skip it. Sorted and skipped, the run records [], [1], [1, 2], [1, 2, 2], [2] and [2, 2]. Combination Sum II uses the same two parts.
6 Cost: count the leaves
The answers are the leaves of the decision tree, and recording each one copies up to n values. So the number of answers sets the time:
| Question | What stops repeats | Answers | Time |
|---|---|---|---|
| Subsets of n | pick or skip, or a start index | 2ⁿ | O(2ⁿ · n) |
| Groups of k from n | a start index | C(n, k) | O(C(n, k) · k) |
| Orders of n | a used array | n! | O(n! · n) |
Factorials grow fastest. At n = 8, n! · n is around 3 × 10⁵ steps. At n = 10 it is around 4 × 10⁷, which still fits. At n = 12 it is around 6 × 10⁹. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE.
So permutations stay practical up to about n = 10, and subsets up to about n = 20. Problems that ask for every answer keep n this small, because the output alone holds that many values.
The tree is never in memory all at once. The call stack holds one path from the top to a leaf, so the depth is n for permutations and k for combinations. With current and used, the extra space is O(n), not counting the answers.
7 Common mistakes
- Recording
currentwithout a copy. Every stored answer is then the one shared list. On [1, 2, 3], the result holds six copies of its final state instead of six orders. - Forgetting to clear
used. On [1, 2, 3],permutereturns only [[1, 2, 3]]. After the first order, every book stays marked, so no other branch can place one. - Skipping duplicates across levels. With
i > 0in place ofi > start, the rule also skips a 2 in the next slot. On [1, 2, 2] it records 4 subsets and loses [2, 2] and [1, 2, 2]. - Mixing up i and i + 1. Combination Sum with i + 1 forbids reuse, so [2, 3, 5] with target 8 finds only [3, 5]. Combinations with i allows reuse, so combine(3, 2) also returns [1, 1], [2, 2] and [3, 3].
8 When to use backtracking
The sign is a question that asks for all of something: every subset, every group, every order, every way to split or fill. Small constraints back it up. Three more problems in this section fit the template once we name a slot and its choices:
| Problem | Each slot | The choices |
|---|---|---|
| Letter Combinations of a Phone Number | the next digit | that digit's letters |
| Generate Parentheses | the next character | ( or ), while it can still balance |
| Palindrome Partitioning | the next piece | where the piece ends, if it is a palindrome |
Some questions have so many dead branches that most of the tree is waste. The next lesson, on pruning, stops those branches before they grow.
Before writing the code, say three things out loud: what one slot is, what its choices are, and what undo must put back.
Practice it
- SubsetsMedium
- PermutationsMedium
- Subsets IIMedium
- Combination SumMedium
- Combination Sum IIMedium
- Letter Combinations of a Phone NumberMedium
- Generate ParenthesesMedium
- Palindrome PartitioningMedium
- CombinationsMedium
- Permutations IIMedium
- Combination Sum IIIMedium
- Gray CodeMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.