1. 程式人生 > >01背包的蠻力法實現

01背包的蠻力法實現

() sub add 中修改 war for set 狀態 amp

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

01背包的蠻力法實現