01背包问题回溯法Java实现
其实回溯法实现01背包问题很简单,没有网上说的那么复杂,简单概括来说就是每次进行搜索如果搜索到叶子节点且符合条件就存储这个值,如果不符合条件就回溯,返回到上一层的背包的容量和所装入的物品价值,这样遇到不符合条件就回溯直到搜索完整个树,最优结果就出来了
代码如下
public class BackTrackingKnapsack01Test {
public int []weight;
public int []value;
public int MaxWeight;
int count;
int []take; //用来标记路径
int []BestChoice;
int curValue=0;
int curWeight=0;
int bestValue=0;
public void init(int []weight,int []value,int MaxWeight){
this.weight = weight;
this.value = value;
this.MaxWeight = MaxWeight;
count = value.length;
BestChoice = new int[count];
take = new int[count];
if (weight==null||weight.length==0||
value==null||value.length==0||
weight.length!=value.length||MaxWeight<0){
System.out.println("参数出现错误");
return;
}
}
public int[] find(int level){
if (level > count-1){
if (curValue>bestValue){
bestValue = curValue;
for (int i=0; i<take.length; i++){
BestChoice[i] = take[i];
}
}
}else {
for (int i=0; i<2; i++){
take[level] = i;
if (i==0){
find(level+1);
}else{
if (curWeight+weight[level]<=MaxWeight){
curWeight+=weight[level];
curValue+=value[level];
find(level+1);
//回溯
curWeight-=weight[level];
curValue-=value[level];
}
}
}
}
return BestChoice;
}
public static void main(String[] args) {
BackTrackingKnapsack01Test B01Test = new BackTrackingKnapsack01Test();
B01Test.init(new int[]{16, 15, 15},new int[]{44,25,20},30);
int[] result = B01Test.find(0);
System.out.print("最佳选择为:[");
for (int i=0; i<result.length;i++){
if (i==result.length-1){
System.out.print(result[i]+"]");
}else {
System.out.print(result[i]+",");
}
}
System.out.print("\n此时价值最大,即"+B01Test.bestValue);
}
}
运行结果: