自己做的背包算法有问题,求解答
后门的东墙 2019-09-08 12:28:02
public class TestBag {
public static void main(String[] args) {
int props = 4;
int bagCapacity = 10;
int[] weights = {6,5,4,5};//6,5,5,4
int[] values = {20,11,8,10};//20,11,10,8
sort(weights,values,props);
System.out.println(opt(props,bagCapacity,weights,values,props-1));
}
/*这是一个递归方法,该方法递归的选择当前物品要不要选择放入背包,返回的值是当前情况下,选或不选的最大价值
* 参数:props:物品的个数
* bagCapacity:背包剩余容量
* weights:物品重量的数组(代表第i个物品的价值为weights[i])
* values:物品价值的数组(代表第i个物品的价值为values[i])
* thePropNo:当前的物品的序列号(第1个,2个...物品) */
public static int opt(int props,int bagCapacity,int[] weights,int[] values,int thePropNo){
if(bagCapacity<=0){
return 0;
}
if(thePropNo<0 || thePropNo >= props){
return 0;
}
if(thePropNo == 0){
if(weights[0] <= bagCapacity){
return values[0];
}else {
return 0;
}
}
//选当前物品
int a = opt(props,bagCapacity-weights[thePropNo],weights,values,thePropNo-1)+values[thePropNo];
//不选当前物品
int b = opt(props,bagCapacity,weights,values,thePropNo-1);
return Math.max(a,b);
}
/*这是一个排序方法,按照价值的降序排列,最终将对应的质量数组和价值数组按照此规则重排了*/
public static void sort(int[] weights,int[] values,int props){
for (int i = 0; i < props; i++) {
for (int j = 0; j < props-1; j++) {
if(values[j] < values[j+1]){
int tmpW = weights[j];
int tmpV = values[j];
weights[j] = weights[j+1];
values[j] = values[j+1];
weights[j+1] = tmpW;
values[j+1] = tmpV;
}
}
}
}