Lecture 19: Dynamic Programming I: Memoization, Fibonacci, Shortest Paths, Guessing
Lecture 19: Dynamic Programming I: Memoization, Fibonacci, Shortest Paths, Guessing
• Examples
– Fibonacci
– Shortest Paths
History
Richard E. Bellman (1920-1984)
Richard Bellman received the IEEE Medal of Honor, 1979. “Bellman . . . explained that
he invented the name ‘dynamid programming’ to hide the fact that he was doing mathe
matical research at RAND under a Secretary of Defense who ‘had a pathological fear and
hatred of the term, research’. He settled on the term ‘dynamic programming’ because it
would be difficult to give a ‘pejorative meaning’ and because ‘it was something not even a
Congressman could object to’ ” [John Rust 2006]
Fibonacci Numbers
F1 = F2 = 1; Fn = Fn−1 + Fn−2
Goal: compute Fn
Naive Algorithm
follow recursive definition
fib(n):
if n ≤ 2: return f = 1
else: return f = fib(n − 1) + fib(n − 2)
=⇒ T (n) = T (n − 1) + T (n − 2) + O(1) ≥ Fn ≈ ϕn
≥ 2T (n − 2) + O(1) ≥ 2n/2
EXPONENTIAL — BAD!
Fn
Fn-1 Fn-2
Fn-2
Fn-3 Fn-3 Fn-4
Memoized DP Algorithm
Remember, remember
memo = { }
fib(n):
if n in memo: return memo[n]
else: if n ≤ 2 : f = 1
else: f = fib(n − 1) + fib(n − 2)
memo[n] = f
return f
POLYNOMIAL — GOOD!
* DP ≈ recursion + memoization
• memoize (remember) & re-use solutions to subproblems that help solve problem
Bottom-up DP Algorithm
⎫
fib = {}
⎪
⎪ Θ(n)
⎪
⎪
⎫ ⎪
⎪
⎪
if k ≤ 2: f = 1
⎪
⎬
Θ(1)
⎬
. . . Fn-2 Fn-1 Fn
[Sidenote: There is also an O(lg n)-time algorithm for Fibonacci, via different techniques]
Shortest Paths
• Recursive formulation:
δ(s, v) = min{w(u, v) + δ(s, u) (u, v) ∈ E}
s t
• recurrence:
• memoize
Guessing
How to design recurrence
s . . . u v
• guess it is (u, v)
• * key: small (polynomial) # possible guesses per subproblem — typically this domi
nates time/subproblem
DAG view
1
time
2
5
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.