Recursion and Backtracking
A recursive call solves a smaller instance. Backtracking explores sibling choices by restoring shared state between branches.
Picture the idea
While planning a timetable, pencil in one class, explore the remaining options and erase that class before trying a different time.
When to use it
Look for repeated subproblems with a decreasing measure, or a small decision tree whose valid leaves are solutions.
How it works
To enumerate subsets, consider one value at each depth. Recurse without it, then with it. Copy the chosen path at a leaf before any later mutation.
- Test a base case.
- Push a call with smaller input.
- Choose, recurse and restore.
- Prune a branch that cannot become valid.
Enumerating all subsets takes Θ(2ⁿ) leaves and O(n) stack depth. Copying every subset costs Θ(n·2ⁿ) total output work.
Watch for this mistake
Sharing one mutable list across all saved answers makes earlier answers change.
Identify both the base case and the quantity that strictly decreases on every recursive edge.