Sub topic 8
Pruning: Abandoning Hopeless Branches Early
This chapter assumes you know the choose-explore-unchoose template and the combination search from the previous chapters. You should also be comfortable reading recursive Python and Big-O notation.
What pruning means
Plain backtracking visits every node in the state-space tree. Pruning is a check that runs before you explore a child. If the check proves the child cannot lead to a valid answer, you skip that child and everything below it.
One test near the root can remove thousands of nodes. The earlier in the tree a check fires, the more work it saves.
Two kinds of checks
| Check type | Question it asks | Example |
|---|---|---|
| Constraint (feasibility) | Does this partial solution already break a rule? | Two queens share a column |
| Bound | Can the remaining choices still reach the goal? | The remaining sum is smaller than the next candidate |
A constraint check rejects a state that is already invalid. A bound check rejects a state that is still valid but cannot be finished.
A worked example
Find every set of k distinct digits from 1 to 9 that adds up to n. The code below counts recursive calls so you can see what pruning saves.
def combo_sum3(k, n, prune=True):
result, path = [], []
calls = 0
def backtrack(start, remaining):
nonlocal calls
calls += 1
if len(path) == k:
if remaining == 0:
result.append(path[:])
return
for i in range(start, 10):
if prune:
if i > remaining:
break # bound: this digit and all larger ones overshoot
if 10 - i < k - len(path):
break # bound: not enough digits left to fill the path
path.append(i)
backtrack(i + 1, remaining - i)
path.pop()
backtrack(1, n)
return result, calls
print(combo_sum3(3, 9, prune=False)) # ([[1, 2, 6], [1, 3, 5], [2, 3, 4]], 130)
print(combo_sum3(3, 9, prune=True)) # ([[1, 2, 6], [1, 3, 5], [2, 3, 4]], 31)Both versions return the same answers. The pruned search makes 31 calls instead of 130.
Break versus continue
When a check depends only on the current candidate, such as "this column is attacked", use continue, because the next candidate might pass.
Common errors
- Pruning too hard. A bound that is too strict throws away real solutions. Before you trust a new check, compare its output against the unpruned version on small inputs.
- Checking too late. If you test a rule only at the leaf, the search is still full enumeration. Move the test to the point where the choice is made.
- An expensive check. If the test costs more than the subtree it removes, the search gets slower. The N-Queens chapter shows how to keep checks at constant time with sets.
Exercise
In combo_sum3, suppose you also add the check "if the smallest possible sum of the remaining slots is greater than remaining, break". For path length p and current digit i, that sum is i + (i+1) + ... + (i + k - p - 1). Why is break, not continue, correct for this check?
Show answer
The minimum possible sum grows as i grows. If it already exceeds remaining for digit i, it also exceeds remaining for every larger digit later in the loop, so none of them can succeed and the loop can stop.
Exercise
The candidates list [7, 2, 6, 3] is used unsorted in a target-sum search that breaks when a candidate is larger than remaining. With target 5, which valid combination is lost?
Show answer
The loop sees 7 first, finds that 7 > 5, and breaks right away, so it never tries [2, 3]. Sorting the list first, or using continue, fixes this.