以下是没有剪枝的算法:
public class Knapsack {
static double C;//背包容量
static double[] P;//物品价值
static double[] W;//物品重量
static int N;//物品个数
static double bestP;
static double currP;
static double currW;
public static void main(String[] args) {
N=4;C=7;
P=new double[]{9.0,10.0,7.0,4.0};
W=new double[]{3.0,5.0,2.0,1.0};
double result=test();
System.out.println("the best result is"+result);
}
public static double test(){
backTrace(0);
return bestP;
}
public static void backTrace(int t){
if(t==N){
System.out.println("this branch CurrentValue:"+currP+"CurrentWeight:"+currW);
if(currW>C)return;
if(currP>bestP)bestP=currP;
return;
}
else
{
currW+=W[t];
currP+=P[t];
backTrace(t+1);
currW-=W[t];
currP-=P[t];
backTrace(t+1);
}
}
}