public class Main {
static int[] goodsWeight = new int[]{10, 20, 30, 40, 50};
static int[] goodsValue = new int[]{10, 60, 20, 40, 70};
public static int calculateMaxValue(int goodsNumber, int leastSpace){
//装完了退出递归
if(goodsNumber == -1){
return 0;
}
int loadValue = 0;
int notLoadValue = 0;
//如果剩余背包容量大于所要装的物体质量
if(leastSpace >= goodsWeight[goodsNumber]){
//装
loadValue = calculateMaxValue(goodsNumber - 1, leastSpace - goodsWeight[goodsNumber]) + goodsValue[goodsNumber];
//不装
notLoadValue = calculateMaxValue(goodsNumber - 1, leastSpace);
//返回最大价值
return loadValue > notLoadValue ? loadValue : notLoadValue;
}
//继续向前查找
return calculateMaxValue(goodsNumber - 1, leastSpace);
}
public static void main(String[] args) {
int maxValue = calculateMaxValue(4, 20);
System.out.println("最大价值为:"+maxValue);
}
}