





































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






































Always remember answers to the sub-problems you've already solved.
The general Method of dynamic programming Fibonacci Series 0/1 Knapsack Problem Finding the actual Knapsack
D ynamic Programming is a general algorithm design technique for solving problems defined by or formulated as recurrences with overlapping sub- instances
0, 1, 1, 2, 3, 5, 8, 13, 21, … f(0) = 0. f(1) = 1. f(N) = f(N-1) + f(N-2) if N 2. int f(int n) { if n < 2 return n else return f(n-1) + f(n-2) } f(7) f(6) f(5) f(5) f(4) f(4) f(3) f(4) f(3)f(3)f(2)f(3)f(2) f(2)f(1) … …^ …^ …^ …^ …^ …^1
Reuse earlier results!
0, 1, 1, 2, 3, 5, 8, 13, 21, … f(0) = 0. f(1) = 1. f(N) = f(N-1) + f(N-2) if N 2. int f(int n) { if n < 2 return n else return f memo (n-1) + f memo (n-2) } f(7) f(6) f(5) f(4) …
Given some items, pack the knapsack to get the maximum total value. Each item has some weight and some value. Total weight that we can carry is no more than some fixed number W. So we must consider weights of items as well as their values. Item # Weight Value 1 1 8 2 3 6 3 5 5
Let’s first solve this problem with a straightforward algorithm Since there are n items, there are 2 n possible combinations of items. We go through all combinations and find the one with maximum value and with total weight less or equal to W Running time will be O( n )
We can do better with an algorithm based on dynamic programming We need to carefully identify the sub-problems
for w = 0 to W V[0,w] = 0 for i = 1 to n V[i,0] = 0 for i = 1 to n for w = 0 to W if w i <= w // item i can be part of the solution if b i
w
for w = 0 to W V[0,w] = 0 for i = 1 to n V[i,0] = 0 for i = 1 to n for w = 0 to W < the rest of the code > What is the running time of this algorithm? O(W) O(W) Repeat n times O(W) + O(n*W) ~ O(n) Remember that the brute-force algorithm takes O( n )
for w = 0 to W V[0,w] = 0 0 0 0 0 0 0 0 1 2 3 0 1 2 3 4 5 4 i\W
for i = 1 to n V[i,0] = 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 0 1 2 3 4 5 4 i\W