Overview
List every set of items that costs exactly the budget by choosing, exploring and undoing, and stop a branch as soon as it costs too much.
- choose, explore, undo
- prune a branch that is already over
- save a copy of the picks
Short Course
Backtracking builds a choice step by step, explores it, then undoes it to try the next one. Prune early: once a basket costs more than the budget, stop that branch. Trap: save a copy of your picks; the list keeps changing.
picks, out = [], []
def choose(i):
if i == 3:
out.append(picks[:]) # a copy!
return
picks.append(i); choose(i + 1); picks.pop()
choose(i + 1)
choose(0) # out: all 8 subsets of 0, 1, 2
Task
Write exact_baskets(prices, budget): every combination of the distinct,
positive prices that adds up exactly to budget, each as a sorted list,
the whole result sorted. Example: exact_baskets([2, 3, 5, 7], 10) →
[[2, 3, 5], [3, 7]].
Test Suites
Pending
Next
Output