forked from learning-zone/java-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapSack.java
More file actions
69 lines (54 loc) · 1.68 KB
/
KnapSack.java
File metadata and controls
69 lines (54 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package DynamicProgramming;
import java.util.ArrayList;
import java.util.Arrays;
public class KnapSack {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] weight = { 7, 3, 4, 5 };
int[] profit = { 42, 12, 40, 25 };
int W = 10;
System.out.println(solve(weight, profit, W, 0));
System.out.println(dp(weight, profit, W));
}
public static int dp(int[] weight, int[] profit, int capacity) {
int n = weight.length;
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= capacity; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (weight[i - 1] <= j) {
dp[i][j] = Math.max(dp[i - 1][j], profit[i - 1] + dp[i - 1][j - weight[i - 1]]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
for (int i = 0; i <= n; i++) {
System.out.println(Arrays.toString(dp[i]));
}
System.out.println(actual_knapsack_item(dp, capacity, n, weight));
return dp[n][capacity];
}
public static ArrayList<Integer> actual_knapsack_item(int[][] dp, int capacity, int n, int[] weight) {
ArrayList<Integer> items = new ArrayList<>();
for (int i = n; i > 0 && capacity > 0; i--) {
if (dp[i][capacity] > dp[i - 1][capacity]) {
items.add(i);
capacity = capacity - weight[i - 1];
}
}
return items;
}
public static int solve(int[] weight, int[] profit, int capacity, int index) {
if (index == weight.length) {
return 0;
}
if (weight[index] <= capacity) {
return Math.max(profit[index] + solve(weight, profit, capacity - weight[index], index + 1),
solve(weight, profit, capacity, index + 1));
} else {
return solve(weight, profit, capacity, index + 1);
}
}
}