0-1揹包問題,在搜索過程中使用遞歸來完成。
package com.test;
class Pack {
int n = 8; //物品個數
int W = 110; //揹包總容量
int[] Weights = {1,11,21,23,33,43,45,55}; //重量數組
int[] Values = {11,21,31,33,43,53,55,65}; //價值數組
int bestValue = 0; //獲得的最大價值
//回溯搜索
void BackTrack(int depth,int preWeights,int preValues){
int currentWeight = preWeights;
int currentValue = preValues;
if(depth >= n){ //達到最大深度
if(bestValue < currentValue){
bestValue = currentValue;
}
return ;
}
if(currentWeight+Weights[depth] < W){ //是否滿足約束條件
currentWeight +=Weights[depth];
currentValue +=Values[depth];
//選取了第i件物品
BackTrack(depth+1,currentWeight,currentValue); //遞歸求解下一個物品
//恢復揹包的容量和價值
currentWeight -= Weights[depth];
currentValue -= Values[depth];
}
//不選取第i件物品
BackTrack(depth+1,currentWeight,currentValue);
}
public int GetBestValue(){
BackTrack(0,0,0);
return bestValue;
}
}
public class Test{
public static void main(String[] args) {
Pack pack = new Pack();
int bestValue = pack.GetBestValue();
System.out.println("揹包內最大物品價值爲:"+bestValue);
}
}