Enumerate Candidates with Backtracking
Core idea
Backtracking explores a decision tree, undoing each temporary choice before trying another. Pruning skips branches proved unable to satisfy the constraint. In a subset search with n items, the unpruned decision tree has 2**n leaves. The example uses nonnegative integers; once a partial sum exceeds a nonnegative target, adding more cannot help.
values = [2,3,4]chosen = []def search(i, total): if total > 5: return if i == len(values): if total == 5: print(chosen.copy()) return chosen.append(values[i]) search(i+1,total+values[i]) chosen.pop() search(i+1,total)search(0,0)The include branch is undone before the exclude branch.
Save independent answers
path = []answers = []for ch in ['A','B']: path.append(ch) answers.append(path.copy()) path.pop()print(answers)Copies preserve each completed candidate after undoing choices.
Common mistake
If negative values are allowed, sum-based pruning may discard a valid branch. Saving the mutable path itself also aliases later changes.
Practice
Find all subsets of [1,2,3] summing to 3; then add -2 and explain which pruning rule must change.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Backtracking
Check your understanding of backtracking.
What is printed?
print(2**4)What is printed?
p=[1]a=[p.copy()]p.pop()print(a)When is pruning justified?
What must happen after a temporary append?