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

来源:互联网 发布:电脑滚动字幕软件 编辑:程序博客网 时间:2024/05/23 02:05

以下是没有剪枝的算法:


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

0 0
原创粉丝点击