This preview shows page 1. Sign up to view the full content.
Unformatted text preview: ted in the order defined by the structure of the problem to lead to a globally optimal solution 3. Postcondition. The globally optimal solution is found. Example To take a closer look at the dynamic programming pattern, we describe some examples that encounter various forces. 1.
2.
3.
4. Fibonacci number Longest common Subsequence (LCS) Unbounded knapsack problem
Shortest Path (Floyd–Warshall algorithm) 1. Fibonacci number Problem. The following recursive relations define the Fibonacci numbers: ⎧
if n = 0
0
⎪
if n = 1 Fn = ⎨
1
⎪ F + F if n > 1
⎩ n −1
n−2
For a given n what would is the Fibonacci number Fn? (1) Find the recursive relation. By definition, we could recursively call Fn‐1 and Fn‐
2 in order to compute Fn. We only need to take care of the corner cases that are the cases when n is 0 or 1. The relation is, of course: ⎧
if n = 0
0
⎪
if n = 1
F ( n) = ⎨
1
⎪ F ( n − 1) + F ( n − 2) if n > 1
⎩ (2) What is the answer of the problem? The answer would be F ( n ) . (3) Try an example to verify the recursive relation. Let’s calculate F (5) . F (5) = F (4) + F (3) = 3 + 2 = 5
F (4) = F (3) + F (2) = 2 + 1 = 3
F (3) = F (2) + F (1) = 1 + 1 = 2
F (2) = F (1) + F (0) = 1 + 0 = 1 (4) Express the recursive relation topdown. function fib(n) begin
if n = 0 then return 0
else if n = 1 then return 1
else return fib(n1) + fib(n2)
end Let’s take a look at the call graph of fib(5). fib(5) fib(4) fib(3) fib(3) fib(2)
fib(1) fib(2) fib(1) fib(0) fib(1) fib(2)
fib(0) fib(1)
fib(1) fib(0) As you can see it evaluates fib(5) in a top‐down way. However, when n is greater than 1 fib(n) calls fib(n1) and fib(n2) consecutively. Even worse, there are redundant calls for fib(3) and fib(2). You could save the previous result of fib(n) and use it in the future. This technique is called memoization, it could benefit your code from an exponential time algorithm to a polynomial time algorithm (5) Use memoization to eliminate redundancy. var m = {0, 1, 1, 1, …}
function fib(n) b...
View
Full
Document
This document was uploaded on 03/17/2014 for the course CS 4800 at Northeastern.
 Fall '12
 KarlLieberherr
 Algorithms

Click to edit the document details