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.cs
using System;
using System.Collections.Generic;
class Program {
static int Fib(int n, Dictionary<int, int> memo) {
if (memo.ContainsKey(n)) {
return memo[n];
}
if (n < 2) {
memo[n] = n;
return n;
}
int value = Fib(n - 1, memo) + Fib(n - 2, memo);
memo[n] = value;
return value;
}
static void Main() {
Dictionary<int, int> memo = new Dictionary<int, int>();
int result = Fib(6, memo);
Console.WriteLine(result);
}
}
Complexity
- Time: O(n) with memoization (vs. O(2^n) without)
- Space: O(n) memo + O(n) call stack
Implementation notes
- The memo is a
Dictionary<int, int>allocated inMainand passed by reference through every recursive call, so all stack frames share one CLR-managed hash table that is reclaimed by GC. - The checked-in code intentionally uses
memo.ContainsKey(n)followed bymemo[n]instead ofTryGetValue, making memo hits replay-visible as a lookup and immediate return. Misses recurse untiln < 2, then writememo[n] = n. - Fibonacci values are
intvalues copied into the dictionary. AfterFib(n - 1, memo) + Fib(n - 2, memo)returns,memo[n] = valuerecords the completed subproblem; the trace separates those writes from later hits.
memoization
A `Dictionary<int, int>` keyed by `n` stores each completed subproblem. Before recursing, check `memo.ContainsKey(n)`: a hit returns immediately, a miss descends.
explicit memo state
The memo is threaded through the recursion as `Dictionary<int, int> memo` so the lesson stays about caching, not global state.