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 complexity analysis from earlier chapters. It also assumes you can read Python decorators such as functools.lru_cache and know Big-O notation. Backtracking is a general tool, and it is often not the fastest one. This chapter covers two situations where a different technique wins, how to spot each one, and what goes wrong if you apply it without care.
Three Kinds of Questions
Search problems usually ask one of three things:
| Question type | Example | What the answer looks like |
|---|---|---|
| Enumeration | "List every subset that sums to 10" | Every solution, written out |
| Decision or counting | "Does any subset sum to 10?" or "How many do?" | One boolean or one number |
| Optimization | "Which subset of items has the highest value under a weight limit?" | One best solution |
Backtracking fits enumeration naturally. If the output itself has exponential size, no algorithm can beat exponential time, and backtracking at least produces each solution without much waste. For decision, counting, and optimization questions, you only need a summary of the solutions, so walking through every branch may be unnecessary.
Overlapping Subproblems: The Case for Dynamic Programming
Consider the question "does some subset of nums sum to target?" A backtracking solution decides, for each index, whether to take that element or skip it. The two counters below compare it with a memoized version on an input that has no solution, which forces a full search.
from functools import lru_cache
def can_sum_backtrack(nums, target):
calls = 0
def bt(i, remaining):
nonlocal calls
calls += 1
if remaining == 0:
return True
if i == len(nums) or remaining < 0:
return False
return bt(i + 1, remaining - nums[i]) or bt(i + 1, remaining)
return bt(0, target), calls
def can_sum_memo(nums, target):
calls = 0
@lru_cache(maxsize=None)
def dp(i, remaining):
nonlocal calls
calls += 1 # counts only cache misses: each distinct state once
if remaining == 0:
return True
if i == len(nums) or remaining < 0:
return False
return dp(i + 1, remaining - nums[i]) or dp(i + 1, remaining)
return dp(0, target), calls
nums = [2] * 16
print(can_sum_backtrack(nums, 33)) # (False, 131071)
print(can_sum_memo(nums, 33)) # (False, 153)The backtracking version makes 2^17 − 1 = 131,071 calls. The memoized version computes only 153 distinct states. The reason is that the path to a state does not matter. Taking element 0 and skipping element 1 leaves the same (i, remaining) pair as skipping element 0 and taking element 1. Backtracking solves that pair again on every path that reaches it. Memoization solves it once.
Dynamic programming (DP) solves a problem by combining stored answers to smaller subproblems. It applies when two conditions hold:
- Overlapping subproblems. Different paths in the state-space tree reach the same state.
- A compact state. The answer for the rest of the search depends only on a small summary of the choices made so far, such as
(index, remaining sum), and not on the full path.
The number of distinct states then bounds the running time. For subset sum, that number is O(n · target), which is far smaller than 2^n when the target is modest.
When DP Does Not Help
Some problems fail the compact-state test. In N-Queens, the remaining work depends on which columns and diagonals are occupied. You could encode that as bitmasks and memoize, but there are so many distinct states that few of them repeat. Word search on a grid is worse, because the state includes the full set of visited cells. When states rarely repeat, a cache costs memory and saves almost nothing.
Enumeration also breaks DP. If you must output every subset that sums to the target, a memo table can tell you which states lead to solutions, but you still have to write each solution out. The output size sets the cost.
Optimization: The Case for Branch and Bound
Branch and bound is backtracking for optimization problems with one extra pruning rule. The search keeps the best complete solution found so far. Before it explores a subtree, it computes an optimistic bound: a value that no solution in that subtree can beat. If the bound is no better than the current best, the whole subtree is skipped.
Ordinary pruning drops branches that are invalid. Branch and bound also drops branches that are valid but cannot win.
The 0/1 knapsack problem shows how this works. The fractional knapsack, which may take part of an item, gives a cheap upper bound. Sort the items by value per unit of weight, fill greedily, and take a fraction of the first item that does not fit.
def knapsack_bb(items, capacity):
# items: list of (value, weight) pairs with positive weights
items = sorted(items, key=lambda it: it[0] / it[1], reverse=True)
n = len(items)
best = 0
def bound(i, value, room):
# Fractional relaxation: no 0/1 choice below can exceed this.
for v, w in items[i:]:
if w <= room:
value += v
room -= w
else:
return value + v * room / w
return value
def bt(i, value, room):
nonlocal best
if value > best:
best = value
if i == n:
return
if bound(i, value, room) <= best:
return # this subtree cannot beat the best found so far
v, w = items[i]
if w <= room:
bt(i + 1, value + v, room - w) # take item i
bt(i + 1, value, room) # skip item i
bt(0, 0, capacity)
return best
print(knapsack_bb([(60, 10), (100, 20), (120, 30)], 50)) # 220What Makes Branch and Bound Fast
How well branch and bound performs depends on two factors:
- Bound tightness. A bound close to the true optimum prunes more. A loose bound, such as "the sum of all remaining values," is still correct but prunes little.
- Finding good solutions early. Pruning compares against
best, so a strong early solution helps every later comparison. Exploring the "take" branch first on items sorted by ratio follows the greedy choice, which is usually close to optimal.
In the worst case, branch and bound is still exponential. It is a heuristic speedup with a correctness guarantee, and it does not improve the complexity class.
Branch and Bound Versus DP for Knapsack
Knapsack also has a DP solution with O(n · capacity) time and space. That bound is pseudo-polynomial: it grows with the numeric value of the capacity, not the number of digits used to write it. With capacity 50, DP is trivial. With capacity 10^9, or with real-valued weights, the table cannot be built, and branch and bound becomes the practical choice.
Decision Criteria
| Signal in the problem | Prefer | Why |
|---|---|---|
| Must output every solution | Backtracking | Output size dominates anyway |
| Yes/no or count answer, and a small state repeats | DP | Each state is solved once |
| State is the whole path (visited cells, placed pieces) | Backtracking with pruning | States rarely repeat, so a cache is wasted memory |
| Optimization with a cheap, tight bound | Branch and bound | Drops valid but losing subtrees |
| Optimization with small integer state | DP | Polynomial in the state count |
| Optimization with huge or real-valued state | Branch and bound | A DP table is infeasible |
Common Failure Modes
- Memoizing a path-dependent function. The cache key leaves out part of the state, so the function returns wrong answers. Every input that affects the result must appear in the key.
- An unsafe bound. If the bound ever underestimates the best value in a subtree (for maximization), branch and bound can prune the optimum and return a wrong answer with no warning. Prove the bound is optimistic.
- Using
<instead of<=in the bound test. Both are correct for finding the best value.<=also prunes ties, which saves work when you need only one optimal solution. - Ignoring memory. A DP over
(i, remaining)with a large target can use gigabytes, while backtracking needs only O(n) stack. Check the size of the state space before you choose DP.
Exercise
You need the number of ways to climb a staircase of n steps taking 1 or 2 steps at a time, for n up to 10,000. A backtracking solution recurses on each choice. Should you use backtracking, DP, or branch and bound, and what is the resulting time complexity?
Show answer
Use DP. The remaining work depends only on the current step, so there are n + 1 states and each one is reached by many paths. Plain backtracking takes O(φ^n) time, which is exponential. DP computes each state once in O(n) time. Write it iteratively (or with O(1) space using two variables), because recursion 10,000 levels deep exceeds Python's default recursion limit. Branch and bound does not apply because this is a counting problem, not an optimization problem.
Exercise
In knapsack_bb, a colleague replaces the fractional bound with "value + the sum of values of all remaining items." Is the result still correct? How does it change running time?
Show answer
It is still correct, because the sum of all remaining values is never less than the best achievable value, so it is still an optimistic bound. It is much looser, though, since it ignores the weight limit. Fewer subtrees fail the test, and the search explores more nodes, in the worst case close to all 2^n.
Exercise
Why would adding @lru_cache to the subsets backtracking function from the earlier chapter (which appends path[:] to a shared result list) produce wrong output?
Show answer
The function returns None and works through side effects on path and result. Its argument, start, does not capture the current path. After the first call with a given start, later calls with the same start return the cached None without running, so the subsets that should have been built from those paths are never appended.