Opening scenario
The Fibonacci sequence starts with
F(0) = 0andF(1) = 1; each later number is the sum of the previous two. Write a recursive function that returnsF(n)for a non-negative integern. Forfib(5), draw one node for each function call and connect it to the calls it makes. Which values does the function compute more than once?Then try Towers of Hanoi:
ndisks are stacked on peg A, largest at the bottom. Move the stack to peg C using peg B as a spare, moving only one top disk at a time and never placing a larger disk on a smaller one. Return the sequence of moves. Can solving the same task forn-1disks help?
These examples introduce two reasons a recursive program can take a long time: repeating the same calculation, and producing a long sequence of required moves. Start by tracing the calls; then consider which work can be avoided.
In the full tutorial
- Question progression
- Canonical Template
- Complexity
- Pattern Recognition Signals
- Practice Set
- Pitfalls
- Variations
- Closing: When to Reach for This