Knap Sack Problem
Knap Sack Problem
The basic idea of dynamic programming is to use a table to store the solutions
of solved sub problems. If you face a sub problem again, you just need to take
the solution in the table without having to solve it again. Therefore, the
algorithms designed by dynamic programming are very effective.
Recursive solution with Dynamic programming-
Top down approach
int knapSack(int W, int[] weights, int[] val, int n, int [][]V) {
if (n == 0 || W == 0)
result= 0;
if(V[n,W] >=0)
return V[n,W]
if (weights[n] > W)
result= knapSack(W, weights, val, n – 1, V);
/* Consider two cases, including item and excluding item.*/
else
result=max((val[n]+ knapSack(W - weights[n], weights, val, n – 1, V)),(knapSack(W, weights, val, n – 1,
V)));
V[n, W]]=result
return result
}
Example
0/1 Knapsack Dynamic Solution-Bottom
up
Example 2
Finding Actual Knapsack items
Knap Sack Problem (Greedy Solution)
Greedy solution does not always gives correct answer for 0/1 knapsack problem.
Greedy solution can be used for fractional knapsack problem. It always given correct answer
for fractional knapsack.
Knap Sack Fractional Problem (Greedy
Solution) Updated