Mental model
To list every subset of {1, 2, 3}, make one decision per value: include it or not. Three yes/no decisions give 2 × 2 × 2 = 8 combinations, and you can draw them as a tree: the root is "nothing decided yet", each level decides one more value, and each of the 8 leaves is a finished subset.
Backtracking is a depth-first walk of that tree. It never builds the tree in memory. It keeps one partial answer (the current path from the root), and at every node it does three things:
- Choose: extend the partial answer with one option.
- Explore: recurse to make the remaining decisions.
- Unchoose: undo the extension, so the partial answer is exactly as it was before the choice.
Then it tries the next option at the same node. When no decisions are left, the partial answer is complete: record a copy.
In the lab, each node appears when its call starts and keeps its place: the layout is computed from the size of the full tree, so nothing moves as the search proceeds. The current node is highlighted, the nodes on the path to it are marked as waiting, and finished leaves carry their answer number.
Subsets: include, then skip
subsets(i, current):
if i == n: record copy of current; return # leaf: every value decided
current.append(values[i]) # choose: include values[i]
subsets(i + 1, current) # explore
current.pop() # unchoose
subsets(i + 1, current) # explore without values[i]
For [1, 2, 3] the answers come out as {1, 2, 3}, {1, 2}, {1, 3}, {1}, {2, 3}, {2}, {3}, {}: "include" is always explored before "skip". The tree has 2ⁿ leaves and 2ⁿ⁺¹ − 1 nodes in total, one call each (the Calls metric).
Permutations: pick any unused value next
A permutation decides "which value goes next" rather than "is this value in". At depth d there are
n − d values left to choose from, so the tree branches n ways, then n − 1, …, then 1, and has n!
leaves. A boolean array used remembers which values are already on the path:
permute(current, used):
if len(current) == n: record copy of current; return
for i in 0 .. n-1:
if used[i]: continue # already on the path
used[i] = true; current.append(values[i]) # choose
permute(current, used) # explore
current.pop(); used[i] = false # unchoose
For [1, 2, 3] the six answers come out in index order: 123, 132, 213, 231, 312, 321. That is the
same order as Python's itertools.permutations and as repeated std::next_permutation calls
starting from sorted indices, which the tests use as references. The lab also counts the
candidates rejected by used[i] (Skipped).
Why unchoose matters
The partial answer is shared by every call. When the "include 1" branch returns, current
must be back to what it was, or the "skip 1" branch would start with a stale 1 in it. Unchoose is
what makes one list serve the whole tree; it is also why the leaf records a copy: the list
itself will keep changing, and storing a reference would leave you with n copies of whatever the
list holds at the end (usually empty).
How much work
| Generating | Answers | Calls (tree nodes) | Time | Extra space |
|---|---|---|---|---|
| Subsets of n | 2ⁿ | 2ⁿ⁺¹ − 1 | O(n · 2ⁿ) | O(n): path + stack |
| Permutations of n | n! | Σₖ n!/(n − k)! ≈ e · n! | O(n · n!) | O(n): path, used, stack |
The n factor in the time is copying each answer (and, for permutations, scanning the used array
at every node). The output itself has that size, so no algorithm that lists every answer can be
asymptotically faster. The stack depth is only n + 1: like every depth-first search, backtracking
holds one root-to-leaf path at a time. These are exponential and factorial costs: 20 values have
about a million subsets, and 12 values already have 479,001,600 permutations. Backtracking is the
right tool when you need every answer or when pruning cuts the tree down.
Pruning
Many problems ask for answers that satisfy a constraint: subsets whose sum is exactly T, placements
of N queens where none attack each other. Backtracking checks the constraint as early as possible
and returns without exploring a branch that cannot lead to a valid answer. With positive values
sorted ascending, a subset-sum search can stop including values as soon as the running sum exceeds
T, and every subtree below that point is never visited. Pruning does not change the worst case,
but it often removes most of the tree in practice. The lab shows the unpruned trees so that every
node is visible; the same choose, explore, unchoose skeleton gains one if for each rule.
Repeated values
With input [1, 1, 2] the code above produces {1, 2} twice (once with each 1) and permutation
[1, 1, 2] twice. The lab therefore asks for distinct values. The standard fix is to sort the
input, then skip a value at a given tree level if an equal value was already tried at that level.
For permutations: if i > 0 and values[i] == values[i - 1] and not used[i - 1]: continue. For
subsets, write the search as "choose the next value from position start onwards" and skip equal
neighbours in that loop.
Language notes
- C#:
current.RemoveAt(current.Count - 1)undoes the choice;[.. current]copies the list. - Python:
current.pop()andcurrent.copy(). For the plain enumeration in production code,itertools.combinationsanditertools.permutationsare faster and lazy. - Java:
current.remove(current.size() - 1)callsremove(int index). With aList<Integer>,remove(Integer.valueOf(x))would instead remove by value: a classic mix-up. - C++:
current.pop_back();output.push_back(current)copies.std::next_permutationenumerates permutations in lexicographic order without recursion.
The teaching implementation
All four languages implement both searches with the same anchored lines as the lab. They read one
shared fixture that fixes the exact order of the answers (empty input, one value, negatives,
unsorted input, four values) and compare 300 random inputs of up to six values with a bitmask
enumeration of subsets and with a permutation reference (itertools.permutations in Python,
std::next_permutation in C++, a count-and-check in C# and Java).
Common mistakes
- Recording
currentinstead of a copy: every recorded answer ends up the same (usually empty). - Forgetting to unchoose, or undoing only half the choice (popping the list but leaving
used[i]set): later branches start from a wrong state. - Unchoosing in the wrong place, for example after the second explore in the subset version.
- Checking a constraint only at the leaves when it could prune much earlier.
- Expecting distinct answers from repeated input without the sort-and-skip rule.
Edge cases
- No values: the root is already a leaf, so there is exactly one answer, the empty subset (or the empty permutation). 2⁰ = 0! = 1.
- One value: subsets {v} and {}; one permutation [v].
Worked practice
1. How many calls does the subset search make for n = 5, and how many answers?
Answer
2⁶ − 1 = 63 calls and 2⁵ = 32 answers: the leaves are half the nodes, plus one.
2. In the permutation search for [a, b, c, d], what is the 7th answer?
Answer
[b, a, c, d]. The first 3! = 6 answers start with a; the 7th is the first that starts with b, and the rest follow in index order.
3. You want all subsets of size exactly k. What can you prune?
Answer
Stop including once current has k values (every deeper "include" exceeds k), and stop when the
values left are too few to reach k (len(current) + (n - i) < k). The search then visits only
nodes on paths to the C(n, k) answers.
Summary
- Backtracking = depth-first search of a decision tree with one shared partial answer.
- Choose, explore, unchoose; record a copy at the leaves.
- Subsets: 2ⁿ answers, 2ⁿ⁺¹ − 1 calls. Permutations: n! answers, about e·n! calls. Stack depth n + 1.
- Pruning skips subtrees that cannot succeed; sorting plus a skip rule handles repeated values.