-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution.java
40 lines (31 loc) · 895 Bytes
/
Solution.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
package dynamic_problem;
/**
* 背包问题
* 记忆化搜索 => DP => DP + 滚动数组 => DP + 优化状态转移方程
* O(n * C)
* O(C)
*/
public class Solution {
public int knapsack(int[] w, int[] v, int C){
if (w == null || v == null || w.length != v.length) {
throw new IllegalArgumentException("illegal argument!");
}
if (C < 0) {
throw new IllegalArgumentException("C is illegal");
}
int n = w.length;
if (n == 0 || C == 0) {
return 0;
}
int[] memo = new int[C + 1];
for (int i = 0; i <= C; i++) {
memo[i] = (i > w[0] ? v[0] : 0);
}
for (int i = 0; i < n; i++) {
for (int j = C; j > w[i]; j--) {
memo[j] = Math.max(memo[j], v[i] + memo[j - w[i]]);
}
}
return memo[C];
}
}