Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Solution {
- /** Recursive code */
- public int knapsack(int W, int val[], int wt[]) {
- return findMaxProfit(W, val, wt, val.length);
- }
- public int findMaxProfit(int W, int val[], int wt[], int n)
- {
- if(n == 0 || W == 0)
- return 0;
- if(wt[n-1] <= W)
- {
- // put the current weight into bag
- int pick = val[n-1] + findMaxProfit(W-wt[n-1], val, wt, n-1);
- int notPick = findMaxProfit(W, val, wt, n-1);
- }
- // when weight exceeds the max weight
- return findMaxProfit(W, val, wt, n-1);
- }
- /** Memoization code */
- public int knapsack(int W, int val[], int wt[]) {
- int n = wt.length;
- // define a matrix as changing paramaters are n and W
- int[][] t = new int[n+1][W+1];
- for(int i=0; i<n+1; i++)
- {
- }
- return findMaxProfit(W, val, wt, val.length, t);
- }
- public int findMaxProfit(int W, int val[], int wt[], int n, int[][] t)
- {
- if(n == 0 || W == 0)
- return 0;
- if(t[n][W] != -1)
- return t[n][W];
- if(wt[n-1] <= W)
- {
- // put the current weight into bag
- int pick = val[n-1] + findMaxProfit(W-wt[n-1], val, wt, n-1, t);
- int notPick = findMaxProfit(W, val, wt, n-1, t);
- return t[n][W];
- }
- // when weight exceeds the max weight
- t[n][W] = findMaxProfit(W, val, wt, n-1, t);
- return t[n][W];
- }
- /** Top-down approach */
- public int knapsack(int W, int val[], int wt[]) {
- int n = wt.length;
- // define a matrix as changing paramaters are n and W
- int[][] t = new int[n+1][W+1];
- // intialise the matrix according to base condition
- for(int i=0; i<n+1; i++)
- {
- for(int j=0; j<W+1; j++)
- {
- if(i==0 || j==0)
- t[i][j] = 0;
- }
- }
- for(int i=1; i<n+1; i++)
- {
- for(int j=1; j<W+1; j++)
- {
- if(wt[i-1] <= j)
- {
- int weight = wt[i-1];
- int pick = val[i-1] + t[i-1][j - weight];
- int notPick = t[i-1][j];
- }
- else
- t[i][j] = t[i-1][j];
- }
- }
- return t[n][W];
- }
- }
RAW Paste Data
Copied
