Recursion and Dynamic Programming
Fibonacci with Memoization
Compute fib(n) recursively. Cache each fib(k) in a memo map so each
subproblem is solved at most once.
Algorithm
Canonical input n = 6 produces fib(6) = 8. Replay highlights every
memo write and every cache hit.
Basic Implementation
Basic.java
import java.util.HashMap;
import java.util.Map;
public class Basic {
public static void main(String[] args) {
Map<Integer, Integer> memo = new HashMap<>();
int result = fib(6, memo);
System.out.println(result);
System.out.println(memo);
}
private static int fib(int n, Map<Integer, Integer> memo) {
if (memo.containsKey(n)) {
return memo.get(n);
}
if (n < 2) {
memo.put(n, n);
return n;
}
int value = fib(n - 1, memo) + fib(n - 2, memo);
memo.put(n, value);
return value;
}
}
Complexity
- Time: O(n) with memoization (vs. O(2^n) without)
- Space: O(n) memo + O(n) call stack
Implementation notes
- Java:
Map<Integer, Integer> memo = new HashMap<>();passed explicitly tofib(int n, Map<Integer, Integer> memo). - The replay shows the call stack on one side and the memo map on the other so memo writes and cache hits are visually distinct.
memoization
A `HashMap<Integer, Integer>` cache stores each completed subproblem. Before recursing, check the memo: a hit returns immediately, a miss descends.
explicit memo parameter
Pass the memo as an explicit parameter so the lesson stays about caching, not language-level scoping.