-
Notifications
You must be signed in to change notification settings - Fork 13
/
Problem01.java
124 lines (112 loc) · 3.52 KB
/
Problem01.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package algorithm.knapsack;
/**
* @author: mayuan
* @desc: 01背包问题
* @date: 2018/09/03
*/
public class Problem01 {
public static void main(String[] args) {
int[] weights = {1, 2, 3, 4, 5};
int[] values = {5, 1, 3, 2, 1};
// System.out.println(knapsack01(5, 5, weights, values));
// System.out.println(knapsack02(5, 5, weights, values));
System.out.println(knapsack03(5, 5, weights, values));
}
/**
* 原始解法
*
* @param numberOfGoods
* @param W
* @param weights
* @param values
* @return
*/
public static int knapsack01(int numberOfGoods, int W, int[] weights, int[] values) {
int[][] dp = new int[numberOfGoods + 1][W + 1];
// 依次对每个物品进行判断
for (int i = 1; i <= numberOfGoods; ++i) {
int w = weights[i - 1];
int v = values[i - 1];
// 依次对容量的每个阶段进行判断
for (int j = W; j >= 1; --j) {
// 该阶段的背包容量可以满足该物品
if (j >= w) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w] + v);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[numberOfGoods][W];
}
/**
* 优化空间
*
* @param numberOfGoods
* @param W
* @param weights
* @param values
* @return
*/
public static int knapsack02(int numberOfGoods, int W, int[] weights, int[] values) {
int[] dp = new int[W + 1];
// 依次对每个物品进行判断
for (int i = 1; i <= numberOfGoods; ++i) {
int w = weights[i - 1];
int v = values[i - 1];
// 依次对容量的每个阶段进行判断
for (int j = W; j >= w; --j) {
// 该阶段的背包容量可以满足该物品
dp[j] = Math.max(dp[j], dp[j - w] + v);
}
}
return dp[W];
}
/**
* 输出选择的物品
*
* @param numberOfGoods
* @param W
* @param weights
* @param values
* @return
*/
public static int knapsack03(int numberOfGoods, int W, int[] weights, int[] values) {
int[][] dp = new int[numberOfGoods + 1][W + 1];
// 依次对每个物品进行判断
for (int i = 1; i <= numberOfGoods; ++i) {
int w = weights[i - 1];
int v = values[i - 1];
// 依次对容量的每个阶段进行判断
for (int j = W; j >= 1; --j) {
// 该阶段的背包容量可以满足该物品
if (j >= w) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w] + v);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
boolean[] record = new boolean[numberOfGoods];
// 倒推选择了哪些物品
int i = numberOfGoods, j = W;
for (; i >= 1; --i) {
int w = weights[i - 1];
int v = values[i - 1];
// 选择了第 i 个物品
if (dp[i][j] == dp[i - 1][j - w] + v) {
record[i - 1] = true;
j -= w;
}
}
for (int n = 0; n < record.length; ++n) {
if (record[n]) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println();
return dp[numberOfGoods][W];
}
}