【发布时间】:2015-03-22 11:17:57
【问题描述】:
我已经添加了背包问题的递归和 DP 的实现。我在其中找不到错误。请帮忙。
import java.util.Scanner;
public class Knapsac {
static int[][] dp;
static int knapsack(int[] size,int[] value, int i, int weight){
if(i <= 0)
return 0;
if(weight < 0)
return Integer.MIN_VALUE;
if(dp[weight][i] != -1)
return dp[weight][i];
dp[weight][i] = Math.max(knapsack(size, value, i-1, weight - size[i]) + value[i], knapsack(size, value, i-1, weight));
return dp[weight][i];
}
static int knapsackWithoutDP(int[] size, int[] value, int i, int weight){
if(i <= 0)
return 0;
if(weight < 0)
return Integer.MIN_VALUE;
return Math.max(knapsackWithoutDP(size, value, i-1, weight - size[i]) + value[i], knapsackWithoutDP(size, value, i-1, weight));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int W, n;
Scanner in = new Scanner(System.in);
W = in.nextInt(); n = in.nextInt();
dp = new int[W+1][n];
for(int i = 0; i < W+1; i++)
for(int j = 0; j < n; j++)
dp[i][j] = -1;
int[] size = new int[n], value = new int[n];
for(int i = 0; i < n; i++){
size[i] = in.nextInt();
value[i] = in.nextInt();
}
System.out.println(knapsackWithoutDP(size, value, size.length-1, W));
System.out.println(knapsack(size, value, size.length-1, W));
}
}
我正在处理测试用例
4 5
1 8
2 4
3 0
2 5
2 3
我应该都得到 13,但我得到了 12。
有人可以帮我理解我的实现中的错误吗?
【问题讨论】:
标签: java algorithm dynamic-programming knapsack-problem