Guest User

Untitled

a guest
Jan 22nd, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. public class Knapsack {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. int val[] = new int[]{0, 60, 100, 120};
  6. int wt[] = new int[]{0, 10, 20, 30};
  7. int W = 50;
  8. int n = val.length-1;
  9. int[][] memo = new int[n+1][W+1];
  10.  
  11. for (int i = 0; i < memo.length; i++) {
  12. for (int j = 0; j < memo[i].length; j++) {
  13. memo[i][j] = -1;
  14. }
  15. }
  16.  
  17. System.out.println(Knapsack.knapsack(wt, val, W, n, memo));
  18. }
  19.  
  20. public static int knapsack(int[] weights, int[] values, int capacity, int index, int[][] memo) {
  21.  
  22. if (memo[index][capacity] != -1) return memo[index][capacity];
  23.  
  24. //base case
  25. if (index <= 0 || capacity <= 0) return 0;
  26.  
  27. int result = 0;
  28.  
  29. if (weights[index] > capacity) {
  30. result = knapsack(weights, values, capacity, index-1, memo);
  31. } else {
  32. int temp1 = knapsack(weights, values, capacity, index-1, memo);
  33. int temp2 = values[index] + knapsack(weights, values, capacity-weights[index], index-1, memo);
  34. result = Math.max(temp1, temp2);
  35. }
  36. memo[index][capacity] = result;
  37. return result;
  38.  
  39. }
  40. }
Add Comment
Please, Sign In to add comment