|
| 1 | +package com.packt.datastructuresandalg.lesson4.knapsack; |
| 2 | + |
| 3 | +public class Knapsack { |
| 4 | + public int recursiveAux(int W, int weights[], int values[], int n) { |
| 5 | + if (n == 0 || W == 0) |
| 6 | + return 0; |
| 7 | + if (weights[n - 1] > W) |
| 8 | + return recursiveAux(W, weights, values, n - 1); |
| 9 | + return Math.max( |
| 10 | + values[n - 1] + |
| 11 | + recursiveAux(W - weights[n - 1], weights, values, n - 1), |
| 12 | + recursiveAux(W, weights, values, n - 1)); |
| 13 | + } |
| 14 | + |
| 15 | + public int recursive(int W, int weights[], int values[]) { |
| 16 | + return recursiveAux(W, weights, values, weights.length); |
| 17 | + } |
| 18 | + |
| 19 | + public int topDownWithMemoizationAux(int W, int weights[], int values[], int n, int[][] memo) { |
| 20 | + if (n == 0 || W == 0) |
| 21 | + return 0; |
| 22 | + if (memo[n][W] == -1) { |
| 23 | + if (weights[n - 1] > W) |
| 24 | + memo[n][W] = topDownWithMemoizationAux(W, weights, values, n - 1, memo); |
| 25 | + else |
| 26 | + memo[n][W] = Math.max( |
| 27 | + values[n - 1] + topDownWithMemoizationAux(W - weights[n - 1], weights, values, n - 1, memo), |
| 28 | + topDownWithMemoizationAux(W, weights, values, n - 1, memo)); |
| 29 | + } |
| 30 | + return memo[n][W]; |
| 31 | + } |
| 32 | + |
| 33 | + public int topDownWithMemoization(int W, int weights[], int values[]) { |
| 34 | + int[][] memo = new int[weights.length + 1][W + 1]; |
| 35 | + for (int i = 0; i <= weights.length; i++) |
| 36 | + for (int j = 0; j <= W; j++) |
| 37 | + memo[i][j] = -1; |
| 38 | + return topDownWithMemoizationAux(W, weights, values, weights.length, memo); |
| 39 | + } |
| 40 | + |
| 41 | + public int bottomUp(int weight, int weights[], int values[]) { |
| 42 | + int[][] dp = new int[values.length + 1][weight + 1]; |
| 43 | + for (int i = 0; i <= values.length; i++) { |
| 44 | + for (int w = 0; w <= weight; w++) { |
| 45 | + if (i == 0 || w == 0) |
| 46 | + dp[i][w] = 0; |
| 47 | + else if (weights[i - 1] <= w) |
| 48 | + dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]); |
| 49 | + else |
| 50 | + dp[i][w] = dp[i - 1][w]; |
| 51 | + } |
| 52 | + } |
| 53 | + return dp[values.length][weight]; |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + int[] weights = {1, 1, 1}; |
| 58 | + int[] values = {10, 20, 30}; |
| 59 | + Knapsack k = new Knapsack(); |
| 60 | + System.out.println("Maximum value = " + k.recursive(2, weights, values)); |
| 61 | + System.out.println("Maximum value = " + k.topDownWithMemoization(2, weights, values)); |
| 62 | + System.out.println("Maximum value = " + k.bottomUp(2, weights, values)); |
| 63 | + } |
| 64 | +} |
0 commit comments