Sub topic 16
When Not to Backtrack: Dynamic Programming and Branch and Bound
This chapter assumes you know the choose-explore-unchoose template, pruning, and the complexity analysis from earlier chapters. It also assumes you have seen a basic dynamic programming table at least once.
Backtracking lists or checks every candidate that survives pruning. That is the right behavior when you need every answer, or when constraints cut the tree down enough. Two kinds of problem break this assumption. In the first, the search keeps solving the same subproblem again and again. In the second, you only need the single best answer.
Overlapping Subproblems: Use Dynamic Programming
Suppose you only need the number of combinations that sum to a target, not the combinations themselves. The backtracking search from the target-sum chapter reaches the state "remaining = 3, starting at index 1" by many different paths. Each time it gets there, it explores the same subtree again. The answer to a subproblem depends only on its state, not on the path that led to it. When that holds, store the answer once and reuse it.
def count_combinations(candidates, target):
# ways[s] = number of combinations (order ignored) summing to s
ways = [0] * (target + 1)
ways[0] = 1
for c in candidates:
for s in range(c, target + 1):
ways[s] += ways[s - c]
return ways[target]
print(count_combinations([2, 3, 6, 7], 7)) # 2This runs in O(n · target) time. The tree search grows exponentially with the target. The trade-off is that dynamic programming gives you a count or an optimum, not the list of solutions. If you need every solution, the output size alone can be exponential, and backtracking is still the honest choice.
Optimization: Use Branch and Bound
Branch and bound is backtracking for optimization problems, such as finding the highest-value set of knapsack items. It keeps the best complete solution found so far. At each node it computes an optimistic bound, which is the best value any completion of this partial solution could possibly reach. If the bound is no better than the current best, the whole subtree is skipped. This differs from constraint pruning, which removes invalid branches. A bound removes valid but losing branches.
def knapsack(items, capacity):
# items: list of (value, weight) pairs with positive weights
items = sorted(items, key=lambda it: it[0] / it[1], reverse=True)
best = 0
def bound(i, weight, value):
# Fractional relaxation: fill greedily, take part of the next item.
for v, w in items[i:]:
if weight + w <= capacity:
weight += w
value += v
else:
return value + v * (capacity - weight) / w
return value
def search(i, weight, value):
nonlocal best
best = max(best, value)
if i == len(items) or bound(i, weight, value) <= best:
return
v, w = items[i]
if weight + w <= capacity:
search(i + 1, weight + w, value + v) # include item i
search(i + 1, weight, value) # exclude item i
search(0, 0, 0)
return best
print(knapsack([(60, 10), (100, 20), (120, 30)], 50)) # 220Exploring the "include" branch first finds good solutions early, which makes later bounds prune harder. The bound must never underestimate the true best. If it does, you can discard the optimal answer.
Choosing an Approach
| Situation | Best fit | Common error |
|---|---|---|
| Enumerate all answers | Backtracking | Adding memoization when results depend on the path |
| Count, or find the optimum, with repeated states | Dynamic programming | A state that is too large to fit in a table |
| Find the optimum, states rarely repeat | Branch and bound | Using a bound that underestimates the true best |
| Feasibility with tight constraints (Sudoku) | Backtracking with heuristics | Forgetting to restore state on failure |
Exercise
You must find the minimum number of coins that make 10,000 from denominations [1, 5, 12, 25]. Should you use backtracking, dynamic programming, or branch and bound, and why?
Show answer
Use dynamic programming. The state (the remaining amount) is a single integer no larger than 10,000, and many coin sequences reach the same remaining amount, so subproblems overlap heavily. A table of size 10,001 solves it in O(4 · 10,000) time. Backtracking, even with a bound, would explore exponentially many sequences.
Exercise
In the knapsack code, what goes wrong if bound() returned only the current value, ignoring the remaining items?
Show answer
The bound would underestimate what the remaining items could add. Any node whose current value is no better than best would be pruned, even when adding more items would beat best. The search would stop almost at once and return a suboptimal answer.