Recursive Algorithms
Recursive Algorithms
006
Massachusetts Institute of Technology
Instructors: Erik Demaine, Jason Ku, and Justin Solomon Lecture 15: Recursive Algorithms
Fibonacci Numbers
• Suppose we want to compute the nth Fibonacci number Fn
• To solve, either:
• A subtlety is that Fibonacci numbers grow to Θ(n) bits long, potentially word size w
Dynamic Programming
• Weird name coined by Richard Bellman
• “Recurse but re-use” (Top down: record and lookup subproblem solutions)
2. Relate subproblem solutions recursively x(i) = f (x(j), . . .) for one or more j < i
4. Base cases
• State solutions for all (reachable) independent subproblems where relation breaks down
5. Original problem
6. Time analysis
P
• x∈X work(x), or if work(x) = O(W ) for all x ∈ X, then |X| · O(W )
• work(x) measures nonrecursive work in relation; treat recursions as taking O(1) time
1
This property often called optimal substructure. It is a property of recursion, not just dynamic programming
Lecture 15: Recursive Algorithms 5
• DAG Relaxation computes the same min values as this dynamic program, just
– step-by-step (if new value < min, update min via edge relaxation), and
– from the perspective of u and Adj+ (u) instead of v and Adj− (v)
Bowling
• Given n pins labeled 0, 1, . . . , n − 1
Bowling Algorithms
• Let’s start with a more familiar divide-and-conquer algorithm:
– Subproblems: B(i, j) = maximum score starting with just pins i, i + 1, . . . , j − 1,
for 0 ≤ i ≤ j ≤ n
– Relation:
∗ m = b(i + j)/2c
∗ Either hit m and m + 1 together, or don’t
∗ B(i, j) = max{vm · vm+1 + B(i, m) + B(m + 2, j), B(i, m + 1) + B(m + 1, j)}
– Topo. order: Increasing j − i
– Base cases: B(i, i) = 0, B(i, i + 1) = max{vi , 0}
– Original: B(0, n)
– Time: T (n) = 4 T (n/2) + O(1) = O(n2 )
• This algorithm works but isn’t very fast, and doesn’t generalize well
(e.g., to allow for a bigger ball that hits three balls at once)
v0 · v1 v1 · v2 v2 · v3
Lecture 15: Recursive Algorithms 7
Bowling Code
• Converting a SRT BOT specification into code is automatic/straightforward
• Here’s the result for the Bowling Dynamic Program above:
For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms