01背包的蛮力法实现

//01背包问题蛮力法
public void backPage(int[] w, int[] v, int iMax)
{
int maxValue=0;//当前最大价值
int weight=0;//当前最大价值对应的重量
List result=null;//当前最优的搭配
ArrayList<ArrayList<Integer>> allSet=new ArrayList<>();//用于保存子集
subSet(0, allSet, w.length);//获得子集,这里的第一个参数主要为了递归实现,当前调用置零。
for (int i = 0; i <allSet.size() ; i++) {//对每一种搭配计算其价值和重量
int temW=0,temV=0;
for (int j = 0; j < allSet.get(i).size(); j++) {
temW+=w[allSet.get(i).get(j)];//当前搭配的重量
temV +=v[allSet.get(i).get(j)];//价值
if(temW<iMax&&temV>maxValue)//是否是最优,是就更新。
{
result=allSet.get(i);
weight=temW;
maxValue=temV;
}
}
}
//输出结果
System.out.println("最佳搭配是:"+result.toString());
System.out.println("重量:"+weight+" 价值:"+maxValue);
}
//求全部子集
private void subSet(int theI, ArrayList<ArrayList<Integer>> resultList, int n)
{
ArrayList<Integer> newArray;
int count=resultList.size();
//每一个元素有进或者不进两种状态,进的话就形成一个新的子集
for (int i =0; i <count ; i++) {//如果循环中修改了list的大小,就不要用size()作为判断,否则死循环
newArray=resultList.get(i);
newArray=(ArrayList<Integer>) newArray.clone();
newArray.add(theI);
resultList.add(newArray);
}
//每一个元素必有单独一个子集
newArray=new ArrayList<Integer>();
newArray.add(theI);
resultList.add(newArray);
if(theI<n-1)subSet(++theI,resultList,n);//用递归求全部子集
}
public static void main(String[] args) {
int[] w={7,3,4,5};
int[] v={42,12,40,25};
new ArrayOption().backPage(w, v, 10);
}

猜你喜欢

转载自www.cnblogs.com/FeeTenno/p/10802780.html