回溯法其实就是用for循环做横向遍历,递归做纵向遍历
0-1背包问题
我们有n种物品,物品j的重量为wj,价格为pj。
我们假定所有物品的重量和价格都是非负的。背包所能承受的最大重量为c。
如果限定每种物品只能选择0个或1个,则问题称为0-1背包问题
public class 背包 {
public int[] w; //物品的重量
public int[] v;//物品的价值
public int n; //物品数目
public int weight; // 当前物品的总重量
public int Bweight; //背包的最大重量
public int curValue; //当前最大价值
public int bestValue; // 最大价值
public int beibao(int i) {
if(i>n-1) {
//此时遍历结束
if(curValue > bestValue) {
bestValue = curValue ;
}
return bestValue;
}
for(int j = 0;j<=n-1;j++) {
// 遍历背包
for (int k =0;k<=1;k++) {
// 记录是否放入背包 0不放 1放
if (k==0) {
beibao(j+1);
}else if(k==1) {
if(weight + w[j]<=Bweight) {
// 当可以放入时
weight += w[j];
curValue += v[j];
beibao(j+1);
// 回溯操作
weight -= w[j];
curValue -= v[j];
}else {
// 背包放不下
beibao(j+1);
}
}
}
}
return bestValue;
}
}