您的位置:首页 > 其它

用回溯法解决0-1背包问题

2015-05-31 15:52 387 查看
以下是没有剪枝的算法:

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);
		}
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: