Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- /** Recursion */
- public int knapSack(int val[], int wt[], int capacity) {
- int n = wt.length;
- return findMaxProfit(capacity, wt, val, n);
- }
- public int findMaxProfit(int W, int[] wt, int[] val, int n)
- {
- // Base case: no items or no remaining capacity
- if(n == 0 || W == 0)
- return 0;
- if(wt[n-1] <= W)
- {
- // pick the item (n stays the same because we can pick it again)
- int pick = val[n-1] + findMaxProfit(W - wt[n-1], wt, val, n);
- // do not pick the item (move to next item)
- int notPick = findMaxProfit(W, wt, val, n-1);
- }
- // current weight exceed max weight, cannot pick the item
- return findMaxProfit(W, wt, val, n-1);
- }
- /** Memoization */
- public int knapSack(int val[], int wt[], int capacity) {
- int n = wt.length;
- int[][] t = new int[n+1][capacity+1];
- for(int i=0; i<n+1; i++)
- return findMaxProfit(capacity, wt, val, n, t);
- }
- public int findMaxProfit(int W, int[] wt, int[] val, int n, int[][] t)
- {
- // Base case: no items or no remaining capacity
- if(n == 0 || W == 0)
- return 0;
- if(t[n][W] != -1)
- return t[n][W];
- if(wt[n-1] <= W)
- {
- // pick the item (n stays the same because we can pick it again)
- int pick = val[n-1] + findMaxProfit(W - wt[n-1], wt, val, n, t);
- // do not pick the item (move to next item)
- int notPick = findMaxProfit(W, wt, val, n-1, t);
- return t[n][W];
- }
- // current weight exceed max weight, cannot pick the item
- t[n][W] = findMaxProfit(W, wt, val, n-1, t);
- return t[n][W];
- }
- /** Top-down approach */
- public int knapSack(int val[], int wt[], int capacity) {
- int n = wt.length;
- int[][] t = new int[n+1][capacity+1];
- // base condition: no items or no remaining capacity
- for(int i=0; i<n+1; i++)
- {
- for(int j=0; j<capacity+1; j++)
- {
- if(i == 0 || j == 0)
- t[i][j] = 0;
- }
- }
- for(int i=1; i<n+1; i++)
- {
- for(int j=1; j<capacity+1; j++)
- {
- if(wt[i-1] <= j)
- {
- // pick the item (n stays the same because we can pick it again)
- int pick = val[i-1] + t[i][j - wt[i-1]];
- // do not pick the item (move to next item)
- int notPick = t[i-1][j];
- }
- // current weight exceed max weight, cannot pick the item
- else
- t[i][j] = t[i-1][j];
- }
- }
- return t[n][capacity];
- }
- }
RAW Paste Data
Copied
