【发布时间】:2021-04-17 18:12:22
【问题描述】:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] val = new int[n];
int [] weight = new int[n];
for(int i =0;i<n;i++){
val[i] = sc.nextInt();
}
for(int i =0;i<n;i++){
weight[i] = sc.nextInt();
}
int cap = sc.nextInt();
int [][]dp = new int[n+1][cap+1];
System.out.println(getMaxVal(val, weight, cap, 0, 0, dp));
}
public static int getMaxVal(int []val, int []wt, int cap, int index, int valStored, int [][]dp){
if(cap == 0 || index >= val.length){
return valStored;
}
if(dp[index][cap] != 0) {
return dp[index][cap];
}
int n = val.length;
int withCurrentItem = 0;
int inittalMaxValue = 0;
if(cap - wt[index] >=0){
withCurrentItem = getMaxVal(val, wt, cap - wt[index], index+1, valStored+val[index], dp);
}
int withoutCurrentItem = getMaxVal(val, wt, cap, index+1, valStored, dp);
dp[index][cap] = Math.max(withoutCurrentItem, withCurrentItem);
return Math.max(withoutCurrentItem, withCurrentItem);
}
}
在这个 0 / 1 背包问题中,如果我在没有 dp 的情况下使用相同的代码,那么它可以完美运行并且我的所有测试用例都通过了。但是如果我喜欢这种方式,我的一些测试用例就会失败。我在这里做错了什么,请帮助我。
【问题讨论】:
-
我建议移除扫描仪并对一些失败的数据进行硬编码。你为调试这个做了什么努力?描述你的整体逻辑/方法是个好主意。
标签: java algorithm data-structures knapsack-problem