Professional Documents
Culture Documents
Algorithms
Dynamic Programming
Examples
• Matrix chain multiplication
CS3230! • Coin changing
• Knapsack problem
Dynamic Programming
Examples
• Matrix chain multiplication
CS3230! • Coin changing
• Knapsack problem
25 10 1
NUM-COINS(3) NUM-COINS(1) ∞
NUM-COINS(3) NUM-COINS(1) ∞
3-3
0 3-5, 3-7
NUM-COINS(3) NUM-COINS(1) ∞
1-3, 1-5, 1-7
3-3
0 3-5, 3-7
NUM-COINS(3) NUM-COINS(1) ∞
1-3, 1-5, 1-7
3-3
0 3-5, 3-7
NUM-COINS(3) NUM-COINS(1) ∞
1-3, 1-5, 1-7
3-3
0 3-5, 3-7
NUM-COINS(3) NUM-COINS(1) ∞
1-3, 1-5, 1-7
3-3
Dynamic Programming
Examples
• Matrix chain multiplication
CS3230! • Coin changing
• Knapsack problem
What is the
maximum
value you
can get?
$15
v1 v2 vn-1 vn
w1 w2 …. wn-1 wn
W-wn
Otherwise, by cut and paste
argument, we can get a better solution
Case 2: Item n (the last one) is not taken
Have optimal solution to subproblem
defined by (w1, v1), …, (wn-1, vn-1), W
v1 v2 vn-1
w1 w2 …. wn-1
W
Otherwise, by cut and paste
argument, we can get a better solution
Recursive solution:
Let m[i,w] be the maximum value that can be
obtained using a subset of items in {1,2,..,i}
with total weight no more than w. Then
# 0 if i = 0 or w = 0
%
m[i, w] = $ max{m[i −1, w − wi ]+ vi , m[i −1, w]} if wi ≤ w
%
& m[i −1, w] otherwise
⊳ Recursive cases
for i ← 1 to n Runtime: Θ(nW)
for j ← 0 to W
if j ≥ w[i] then
m[i, j] ← max{m[i-1, j-w[i]]+ v[i],m[i-1, j]}
else
m[i, j] ← m[i-1, j]
58
v[1..5] = {4, 2, 10, 1, 2}
w[1..5] = {12, 1, 4, 1, 2}
W = 15
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0
2 0
3 0
4 0
5 0
59
#
% 0 if i = 0 or w = 0
m[i, w] = $ max{m[i −1, w − wi ]+ vi , m[i −1, w]} if wi ≤ w
%
& m[i −1, w] otherwise
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4
✔ 2 0 2 2 2 2 2 2 2 2 2 2 2 4 6 6 6
✔ 3 0 2 2 2 10 12 12 12 12 12 12 12 12 12 12 12
✔ 4 0 2 3 3 10 12 13 13 13 13 13 13 13 13 13 13
✔ 5 0 2 3 4 10 12 13 14 15 15 15 15 15 15 15 15
Analysis and Design of Algorithms 64
Is KNAPSACK in P?