|
| 1 | +/* |
| 2 | +https://www.techiedelight.com/0-1-knapsack-problem/ |
| 3 | +https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ |
| 4 | +*/ |
| 5 | + |
| 6 | +/* |
| 7 | +In the 0/1 Knapsack Problem we must include an item entirely or exclude the item with an objective of maximizing profit/value constrainted by the size of the knapsack. |
| 8 | +
|
| 9 | +If the problem is not 0/1 knapsack and we are allowed to split items, we can take a greedy approach |
| 10 | +we can chose items by sorting items according to profit per unit weight. |
| 11 | +In doing so, only the last element or a single element will have to be split. |
| 12 | +*/ |
| 13 | + |
| 14 | +/*RECURSION |
| 15 | +For each item we have 2 choices - |
| 16 | +1. Include the item and recur for the remaining item. Here the capacity of the knapsack is reduced. |
| 17 | +2. Exclude the item and recur for the remaining item. Capacity of knapsack remains the same. |
| 18 | +
|
| 19 | +*/ |
| 20 | + |
| 21 | +public int knapsack(int W, int item, int wt[], int val[]){ |
| 22 | + //BASE CASE: we have exhausted all items or we have utilized the entire capacity of knapsack |
| 23 | + if(n==0 || W==0) return 0; |
| 24 | + |
| 25 | + //If the weight of current item exceeds the capacity of knapsack it can not be included - EXCLUDE ITEM |
| 26 | + else if(wt[n-1] > W) return knapsack(W, item-1, wt, val); |
| 27 | + |
| 28 | + //Try both - INCLUDE AND EXCLUDE - chose the best |
| 29 | + else return Math.max(knapsack(W, item-1, wt, val), val[item-1] + knapsack(W-wt[item-1], item-1, wt, val)) |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +/* |
| 34 | +Time Complexity - O(2^n) |
| 35 | +For each item we are exploring the two choices(We include and exclude each item) to find the best. |
| 36 | +*/ |
| 37 | + |
| 38 | +/* |
| 39 | +DYNAMIC PROGRAMMING - BOTTOM UP APPROACH |
| 40 | +*/ |
| 41 | + |
| 42 | +public int knapsack(int W, int item, int wt[], int val[]){ |
| 43 | + int k[][] = new int[item+1][W+1]; |
| 44 | + |
| 45 | + for(int i=0;i<=item;i++){ |
| 46 | + for(int j=0) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | + |
0 commit comments