Dynamic Programming: We'd Like To Have "Generic" Algorithmic Paradigms For Solving Problems
Dynamic Programming: We'd Like To Have "Generic" Algorithmic Paradigms For Solving Problems
Examples:
Mergesort,
Quicksort,
Strassens algorithm
...
Dynamic Programming: Appropriate when you have recursive subproblems that are not independent
You want to make change for n cents, using the smallest number of coins.
Example: U.S. coins
d1 = 1 d2 = 5 d3 = 10 d4 = 25
Solution
We will only concentrate on computing the number of coins. We will
later recreate the solution.
Let C[p] be the minimum number of coins needed to make change for
p cents.
Let x be the value of the first coin used in the optimal solution.
Then C[p] = 1 + C[p x] .
Problem:
We dont know x.
Solution
We will only concentrate on computing the number of coins. We will
later recreate the solution.
Let C[p] be the minimum number of coins needed to make change for
p cents.
Let x be the value of the first coin used in the optimal solution.
Then C[p] = 1 + C[p x] .
Problem:
Answer:
We dont know x.
We will try all possible x and take the minimum.
C[p] =
C[p] =
1
2
3
4
5
6
Change(p)
if (p < 0)
then return
elseif (p = 0)
then return 0
else
return 1 + min{Change(p 1), Change(p 5), Change(p 10)}
1
2
3
4
5
6
7
8
9
10
11
12
DP-Change(n)
C[< 0] =
C[0] = 0
for p = 2 to n
do min =
for i = 1 to k
do if (p di)
then if (C[p di]) + 1 < min)
then min = C[p di] + 1
coin = i
C[p] = min
S[p] = coin
Running Time:
O(nk)
Dynamic Programming
Used when:
Optimal substructure
Overlapping subproblems
Methodology
Characterize structure of optimal solution
Recursively define value of optimal solution
Compute in a bottom-up manner