Learn / Recursion and backtracking
Recursion trees
Many problems build an answer one choice at a time: the next bracket, the next letter, the next part of an IP address. Drawing those choices as a tree makes the code obvious. Each node is a partial answer, each branch is one choice, and each leaf is a finished answer. The recursion walks the tree, and a rule prunes branches that can never work.
How to recognise it
- The question says "generate all", "list every", or "all possible" strings or combinations.
- The answer is built step by step, and each step has a small number of choices.
- Some partial answers can be ruled out early (too many closing brackets, a part bigger than 255).
The idea in one picture
Write the empty answer at the top of a page. Below it, draw one branch for every choice you could make first. Below each of those, a branch for every second choice, and so on. The finished answers are the leaves. The recursion is just a walk over this drawing, left to right.
| Problem | One level of the tree | Pruning rule |
|---|---|---|
| Generate Parentheses | add ( or ) | ( while open is below n, ) while close is below open |
| Letter Combinations | pick a letter of the next digit | none needed |
| IP addresses | take the next 1, 2 or 3 digits as a part | no leading zero, at most 255, exactly 4 parts |
| Sentences from word lists | pick a word from the next list | none needed |
| Remove Invalid Parentheses | remove one more bracket (breadth-first) | stop at the first level with a valid string |
Template: choose, recurse, undo
function build(state):
if state is a complete answer: record it; return
for each choice allowed from state:
apply choice
build(state)
undo choice
Counting the work
The number of leaves is the product of the choices per level, so these trees grow fast. That is expected: when the question asks for every answer, the output itself is that big. Pruning cuts away whole subtrees that cannot lead to a valid answer.
Common mistakes
- Forgetting to undo, so one branch's choice leaks into the next.
- Recording an answer by reference (a shared list) instead of a copy.
- Pruning too late: checking validity only at the leaf costs far more than stopping as soon as a rule breaks.
Problems
- Generate Parenthesesmediumguide ready
- Letter Combinations of a Phone Numbermediumguide ready
- Program to generate all possible valid IP addresses from given stringmediumguide ready
- Recursively print all sentences that can be formed from list of word listsmediumguide ready
- Remove Invalid Parentheseshardguide ready