-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
Knapsack01.java
45 lines (40 loc) · 1.26 KB
/
Knapsack01.java
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
package algo.dp;
/**
* Created by sherxon on 3/15/17.
*/
public class Knapsack01 {
public static void main(String[] args) {
knapsack(new int[]{1, 4, 5, 7}, new int[]{1, 3, 4, 5}, 7);
}
static void knapsack(int[] values, int[] weights, int k) {
int[][] a = new int[values.length][k + 1];
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a[i].length; j++) {
if (i == 0) {
if (weights[i] <= j)
a[i][j] = values[i];
} else {
if (j < weights[i])
a[i][j] = a[i - 1][j];
else
a[i][j] = Math.max(a[i - 1][j], values[i] + a[i - 1][j - weights[i]]);
}
}
}
print(a);
}
private static void print(int[][] a) {
for (int i = 0; i < a.length; i++) {
if (i == 0) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(j + " ");
}
System.out.println();
}
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}