DynamicProgramming1
DynamicProgramming1
Dynamic Programming
DP #1: Rod Cutting
DP #2: Stamp Problem
DP #3: Matrix-Chain Multiplication
DP #4: Sequence Alignment Problem
Longest Common Subsequence (LCS) / Edit Distance
Viterbi Algorithm
Space Efficient Algorithm
3
4
“Dynamic”: time-varying
“Programming”: a tabular method
Dynamic Programming: planning over time
5
Divide-and-Conquer Dynamic Programming
partition the problem into partition the problem into
independent or disjoint dependent or overlapping
subproblems subproblems
repeatedly solving the common avoid recomputation
subsubproblems Top-down with memoization
more work than necessary Bottom-up method
6
Apply four steps
1. Characterize the structure of an optimal solution
2. Recursively define the value of an optimal solution
3. Compute the value of an optimal solution, typically in a bottom-
up fashion
4. Construct an optimal solution from computed information
7
Fibonacci(n)
Fibonacci sequence (費波那契數列) if n < 2 // base case
Base case: F(0) = F(1) = 1 return 1
// recursive case
Recursive case: F(n) = F(n-1) + F(n-2) return Fibonacci(n-1)+Fibonacci(n-2)
F(5)
F(3) was computed twice
F(4) F(3)
F(2) was computed 3 times
F(5)
F(3) F(2)
n 0 1 2 3 4 5
F(2) F(1)
F(n) 1 1 ?2 3? ?5 ?8
F(1) F(0)
9
Avoid recomputation of the same subproblems using memo
Memoized-Fibonacci(n)
// initialize memo (array a[])
a[0] = 1
a[1] = 1
for i = 2 to n
a[i] = 0
return Memoized-Fibonacci-Aux(n, a)
Memoized-Fibonacci-Aux(n, a)
if a[n] > 0
return a[n]
// save the result to avoid recomputation
a[n] = Memoized-Fibonacci-Aux(n-1, a) + Memoized-Fibonacci-Aux(n-2, a)
return a[n]
10
Building up solutions to larger and larger subproblems
F(5)
Bottom-Up-Fibonacci(n)
if n < 2
F(4) return 1
a[0] = 1
a[1] = 1
F(3) for i = 2 … n
a[i] = a[i-1] + a[i-2]
return a[n]
F(2)
F(1)
F(0)
11
Avoid recomputation of the same subproblems
Principle of Optimality
Any subpolicy of an optimum policy must itself be an optimum policy with
regard to the initial and terminal states of the subpolicy
Two key properties of DP for optimization
Overlapping subproblems
Optimal substructure – an optimal solution can be constructed from optimal
solutions to subproblems
Reduce search space (ignore non-optimal solutions)
12
Shortest Path Problem
Input: a graph where the edges have positive costs
Output: a path from S to T with the smallest cost
M
C’SM < CSM?