【发布时间】:2018-05-16 11:08:25
【问题描述】:
是否有一种算法可以确定具有精确重量 W 的背包? IE。这就像正常的 0/1 背包问题,有 n 个项目,每个项目的重量为 w_i,价值为 v_i。最大化所有物品的价值,但是背包中物品的总重量需要正好有重量W!
我知道“正常”的 0/1 背包算法,但这也可以返回重量更轻但价值更高的背包。我想找到最高值但准确的 W 重量。
这是我的 0/1 背包实现:
public class KnapSackTest {
public static void main(String[] args) {
int[] w = new int[] {4, 1, 5, 8, 3, 9, 2}; //weights
int[] v = new int[] {2, 12, 8, 9, 3, 4, 3}; //values
int n = w.length;
int W = 15; // W (max weight)
int[][] DP = new int[n+1][W+1];
for(int i = 1; i < n+1; i++) {
for(int j = 0; j < W+1; j++) {
if(i == 0 || j == 0) {
DP[i][j] = 0;
} else if (j - w[i-1] >= 0) {
DP[i][j] = Math.max(DP[i-1][j], DP[i-1][j - w[i-1]] + v[i-1]);
} else {
DP[i][j] = DP[i-1][j];
}
}
}
System.out.println("Result: " + DP[n][W]);
}
}
这给了我:
Result: 29
(请问我的问题是否有任何不清楚的地方!)
【问题讨论】:
-
只需将
DP[i][j] = DP[i-1][j];切换为DP[i][j] = -infinity -
@greybeard 哎呀
标签: java algorithm dynamic-programming knapsack-problem