Sub topic 12
Cutting the Search Short: Pruning and Backtracking
This chapter assumes you can write recursive functions in Python, know the bitmask subset enumeration from the earlier chapter, and can read Big-O notation. The goal is to make an exhaustive search visit fewer candidates while still returning the correct answer.
The Idea: Abandon Hopeless Branches
The bitmask subset-sum solution builds every one of the 2^n subsets in full before checking any of them. Many of those subsets were already doomed after their first few choices. For example, once the running total passes the target and every item is non-negative, no later choice can bring the total back down.
Backtracking changes the order of the work. You build a candidate one decision at a time and check it after each decision. Pruning is the check that says "no completion of this partial candidate can succeed", so the search stops exploring that branch. When a branch is pruned or fully explored, the search backtracks: it undoes the last decision and tries the next alternative.
For subset sum, each level of the recursion decides whether to include or exclude one item. That gives the same 2^n search space as the bitmask version, but the search walks it as a tree and can cut off whole subtrees.
Two Pruning Rules for Subset Sum
With non-negative items, two rules are safe:
- Overshoot: if
remaining < 0, the sum is too large, and adding more items only makes it larger. - Undershoot: if
remainingis larger than the sum of all items not yet decided, even taking every one of them cannot reach the target.
Sorting the items in descending order makes both rules fire sooner, because the large items get decided near the top of the tree.
def subset_sum_pruned(items, target):
# Assumes all items are non-negative.
items = sorted(items, reverse=True)
suffix = [0] * (len(items) + 1)
for i in range(len(items) - 1, -1, -1):
suffix[i] = suffix[i + 1] + items[i]
calls = 0
def search(i, remaining):
nonlocal calls
calls += 1
if remaining == 0:
return True
if remaining < 0 or remaining > suffix[i]:
return False
return search(i + 1, remaining - items[i]) or search(i + 1, remaining)
return search(0, target), calls
print(subset_sum_pruned([5, 3, 2], 4)) # (False, 6)
print(subset_sum_pruned(list(range(1, 21)), 3)) # (True, ...)
print(subset_sum_pruned([2] * 20, 41)) # (False, 1)suffix[i] holds the sum of items[i:]. When i == len(items), suffix[i] is 0, so any positive remainder fails the undershoot test. That one test also covers the "ran out of items" base case. In the last call, 41 is larger than the total of 40, so the search stops at the root instead of checking about a million subsets.
What Pruning Does and Does Not Buy You
| Property | Bitmask enumeration | Pruned backtracking |
|---|---|---|
| Worst-case time | O(n · 2^n) | O(2^n) |
| Typical time | Always the full cost | Often far less |
| Correctness depends on | Nothing extra | Every prune rule being valid |
| Easy to stress-test | Yes | Yes, against the bitmask version |
Pruning usually leaves the worst case exponential. An adversarial input can keep every branch alive. Do not use pruning to justify an n that the complexity estimate rules out. Its value is a large speedup on typical inputs.
The General Pattern
Most backtracking searches have the same shape:
- Choose: extend the partial candidate by one decision.
- Check: if the partial candidate cannot lead to a solution (or, in an optimization problem, cannot beat the best found so far), return.
- Recurse, then undo the choice and try the next option.
For the traveling-salesman search, the check is "the cost of the partial route is already at least best". Pruning against the best answer found so far is called branch and bound.
Exercise
Run subsetsumpruned([4, -3, 2], 1). Is the answer correct? Which rule causes the failure, and why?
Show answer
It returns False, but {-3, 4} sums to 1. After sorting the items are [4, 2, -3]. Taking 4 gives remaining = -3, and the overshoot rule prunes that branch even though adding -3 later would bring the total back to exactly 1. The undershoot rule also breaks, because suffix sums no longer give an upper bound on what the remaining items can add. Both rules require non-negative items.
Exercise
Adapt shortest_tour into a backtracking search that builds the route one city at a time and prunes any partial route whose cost is already >= best. Why is it still correct?
Show answer
Keep a visited set and a running cost. Recurse to each unvisited city, adding dist[last][next]. Prune when cost >= best. When every city is visited, add dist[last][0] and update best. The search stays correct because distances are non-negative, so extending a partial route can never lower its cost, and a pruned route cannot beat best.