Sub topic 12
Cutting the Search Short: Pruning and Backtracking
This chapter assumes you can write recursive functions in Python and read Big-O notation. It also assumes you have seen the bitmask subset enumeration and the permutation-based tour search from earlier chapters. Those solutions visit every candidate, and the goal here is to visit fewer candidates while still returning exactly the same answers.
The Idea: Abandon Hopeless Partial Candidates
A bitmask enumeration builds each subset in full before checking it. If the first two items you chose already exceed the target, the loop still evaluates every subset that contains those two items, and there can be millions of them.
Backtracking builds a candidate one decision at a time and checks it at each step. Each decision is something like "include item i or not" or "which city comes next". The partial candidate is called a prefix. If the prefix cannot extend to any valid solution, you drop it along with every completion of it. Dropping a branch this way is called pruning. Backtracking means undoing the last decision and trying the next alternative.
The search space is the same one the brute force enumerates. Pruning only changes how much of it you walk.
The Search Tree
A recursive enumeration of subsets traces a binary tree. Depth i corresponds to the decision about item i. Every leaf is one complete subset, so a full walk visits 2^n leaves. A prune at a node removes its whole subtree, and a prune near the root removes most of the tree.
Subset Sum with a Feasibility Prune
Here is the backtracking subset-sum solver, rewritten to record the subset it finds. Note the explicit choose, recurse, un-choose steps.
def find_subset(items, target):
# Assumes all items are non-negative.
items = sorted(items, reverse=True)
path = []
def search(i, remaining):
if remaining == 0:
return True
if i == len(items) or remaining < 0:
return False
path.append(items[i]) # choose
if search(i + 1, remaining - items[i]):
return True
path.pop() # un-choose (backtrack)
return search(i + 1, remaining) # try the other branch
return list(path) if search(0, target) else None
print(find_subset([3, 34, 4, 12, 5, 2], 9)) # [5, 4]
print(find_subset([3, 34, 4, 12, 5, 2], 30)) # NoneThe prune is remaining < 0. It is sound only because every item is non-negative. Once the running sum passes the target, adding more items can never bring it back down. Sorting in descending order makes the prune fire earlier: large items push remaining negative near the root, where each cut removes a big subtree.
A Stronger Prune and Measuring Its Effect
A second sound test is the bound check "even taking everything left is not enough". If the sum of items[i:] is less than remaining, no completion can reach the target. Precompute suffix sums so the check costs O(1). Count the calls so you can see what each prune buys.
def subset_sum_counted(items, target, prune=True):
items = sorted(items, reverse=True)
n = len(items)
suffix = [0] * (n + 1)
for i in range(n - 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 i == n:
return False
if prune and (remaining < 0 or suffix[i] < remaining):
return False
return search(i + 1, remaining - items[i]) or search(i + 1, remaining)
found = search(0, target)
return found, calls
items = [3, 34, 4, 12, 5, 2]
for prune in (False, True):
print("prune" if prune else "no prune",
subset_sum_counted(items, 100, prune),
subset_sum_counted(items, 9, prune))For target 100, the unpruned search makes 127 calls, the full tree of depth 6, and the pruned search makes 1. All six items sum to 60, so the suffix check rejects the root. For target 9, both versions return True with far fewer calls than 127. Run the code to see the exact counts. On a small input like this the gap is modest. With 30 or 40 items, the same prunes often separate a search that finishes instantly from one that never finishes.
Kinds of Pruning
| Prune type | Question it asks | Example | Soundness requirement |
|---|---|---|---|
| Feasibility | Has this prefix already broken a constraint? | Running sum exceeds target | Constraint cannot be repaired by later choices |
| Bound | Can any completion still reach the goal? | Suffix sum is less than remaining | Bound must be optimistic (never understate what is reachable) |
| Branch and bound | Can any completion beat the best answer found so far? | Partial tour cost ≥ best tour | Costs only grow as the prefix extends |
| Symmetry | Is this branch equivalent to one already tried? | Fix city 0 as the tour start; skip equal duplicate values | Equivalence must be exact |
| Ordering | Which branch should I try first? | Largest items first | Never affects correctness, only speed |
Ordering is a heuristic, not a prune. It changes how soon the other prunes fire and, for optimization problems, how quickly you find a good incumbent.
Branch and Bound for the Traveling Salesman
The permutation solution from the earlier chapter evaluates all (n-1)! tours. Branch and bound builds each tour one city at a time and keeps best, the cheapest complete tour found so far. A partial tour that already costs at least best can only get more expensive, assuming non-negative distances, so it is pruned.
import itertools
import math
import random
def shortest_tour_bnb(dist):
# Assumes non-negative distances.
n = len(dist)
best = math.inf
visited = [False] * n
visited[0] = True
def extend(city, count, cost):
nonlocal best
if cost >= best:
return # bound prune
if count == n:
best = min(best, cost + dist[city][0]) # close the tour
return
for nxt in range(1, n):
if not visited[nxt]:
visited[nxt] = True
extend(nxt, count + 1, cost + dist[city][nxt])
visited[nxt] = False # backtrack
extend(0, 1, 0)
return best
def shortest_tour(dist):
n = len(dist)
best = math.inf
for perm in itertools.permutations(range(1, n)):
route = (0,) + perm + (0,)
best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
return best
dist = [[0, 2, 9, 10],
[1, 0, 6, 4],
[15, 7, 0, 8],
[6, 3, 12, 0]]
print(shortest_tour_bnb(dist)) # 21 (0 -> 2 -> 3 -> 1 -> 0)
for _ in range(300):
n = random.randint(1, 7)
d = [[0 if a == b else random.randint(1, 20) for b in range(n)]
for a in range(n)]
assert shortest_tour_bnb(d) == shortest_tour(d), d
print("branch and bound matches brute force")The last loop reuses the stress-testing idea from earlier in the tutorial. The plain permutation search acts as the oracle, and the pruned version has to agree with it on hundreds of random instances. Every new prune adds a chance to discard a real answer, so this check matters most right after you add one.
Common Errors
Forgetting to undo state
Backtracking code that mutates shared state, such as path, visited, or a board, must restore that state after each recursive call returns. If you leave out visited[nxt] = False, the first branch's choices stay marked and block all later branches. The program still runs and returns a wrong answer, which makes this bug hard to spot. Two habits help: put the undo on the line directly after the recursive call, or pass immutable values (like remaining) that need no undo.
Pruning with `>` when you need `>=`, or the reverse
In branch and bound, cost >= best is safe when you want any one optimal tour, because an equal-cost tour cannot improve the answer. If the task is to count or list every optimal tour, the prune must be cost > best, or you will skip ties.
Early return in counting problems
The or in search(...) or search(...) stops at the first solution. That is correct for "does one exist?" and wrong for "how many are there?". Counting versions must explore both branches and add the results, and pruning has to stay limited to branches with zero solutions.
Prunes based on hunches
"This branch probably won't help" is not a prune. A prune needs a short proof that the subtree holds no valid or better answer. If you cannot state that proof in a sentence, treat the idea as an ordering heuristic instead.
What Pruning Does Not Change
Pruning does not change the worst-case complexity. An adversarial subset-sum instance, such as all items equal and an unreachable odd target, can still force close to 2^n calls. Branch and bound for the traveling salesman stays exponential in the worst case too. In practice, pruning can raise the input size you can handle. A pruned subset search often copes with 35 to 45 items where a plain bitmask stalls past about 25, but no input limit is guaranteed.
When the input limits push past that, look at the search for repeated work rather than more prunes. Subset sum revisits the same (i, remaining) state through many different prefixes. Memoizing those states, as covered in the optimization chapter, turns the exponential search into an O(n · target) dynamic program. Pruning and memoization work together: pruning skips states that cannot succeed, and memoization avoids repeating states you have already solved.
Exercise
A teammate adds the prune if remaining < 0: return False to a subset-sum backtracker whose input may contain negative integers. Give a concrete input where the pruned version returns the wrong answer, and explain why.
Show answer
Take items [5, -3] with target 2, and suppose the search tries 5 first. Choosing 5 from remaining 2 gives remaining -3, which the prune rejects. Without the prune, the search would go on to choose -3 and reach remaining 0, a valid subset {5, -3}. Skipping 5 leaves only -3 or the empty subset, and neither sums to 2. So the pruned search returns False although a solution exists. The prune assumes the running sum can only grow, which is false when negative items are allowed.
Exercise
Modify the counting idea so the function returns the number of subsets of non-negative items that sum exactly to target, keeping both the remaining < 0 and suffix-sum prunes. What must change besides the return value, and is the suffix prune still sound?
Show answer
Replace search(...) or search(...) with search(i + 1, remaining - items[i]) + search(i + 1, remaining), return 1 when a subset is complete with remaining == 0, and return 0 for pruned or exhausted branches. Because zero-valued items can still be added or skipped, the remaining == 0 check should only count at i == n. Otherwise, check remaining == 0 at i == n and keep recursing while i < n. Both prunes stay sound, because each only cuts subtrees that provably contain zero valid subsets.
Exercise
In shortesttourbnb, why does trying nearer cities first (sorting candidates nxt by dist[city][nxt]) speed up the search without affecting correctness?
Show answer
Visiting nearby cities first tends to produce a cheap complete tour early, which lowers best sooner. A lower best makes the cost >= best prune fire higher in the tree for every later branch. The order of the loop only changes when branches are explored, not which ones are skipped for a valid reason, so the minimum returned is unchanged.