回溯法实现01背包问题(递归版)
老师今天让我们上机实验做这个,还是有点把握的。毕竟认真听课了嘛。回溯法其实就是套公式(个人理解)。
来自清华大学出版社的《算法与分析》的解题步骤
(1) 针对所给问题,定义问题的解空间;
(2)确定易于搜索的解空间结构(解空间树);
(3)以深度优先的方式搜索解空间树,并且在搜索过程中用剪枝函数避免无效搜索;
直接贴代码了,里面有较为详细的注释~
package bag;
import java.text.DecimalFormat;
import java.util.Arrays;
public class bagTest {
public static void main(String []args){
double c=20;
int n=10;
double []weight={5,5,3,4,5,1,2,4,3,2};
double []value={5,4,3,2,1,10,1,5,4,3};
/* double []weight=new double[n];
double []value=new double[n];
for(int i=0;i<n;i++){
普通双精度随机数
* double random1=Math.random()*100;
double random2=Math.random()*100;
//只有两位小数的双精度数
double random1=(double)Math.round((Math.random()*10+1)*100)/100;
double random2=(double)Math.round((Math.random()*10+1)*100)/100;
weight[i]=random1;
value[i]=random2;
}*/
bag b=new bag(c,n,weight,value);
}
}
class bag{
private double c;
private int n;
private double []weight;
private double []value;
//存储排序后的编号
private int []x;
//最终选择的物品组
private StringBuffer result;
//完整解(最大价值)
private double max;
//部分解(当前最大值)
private double pv;
//当前重量
private double pw;
public bag(double c ,int n,double []weight, double []value){
this.c=c;;
this.n=n;
this.weight=weight;
this.value=value;
x=new int[n];
result=new StringBuffer();
max=0;