1. 程式人生 > 實用技巧 >JavaScript事件代理(事件委託)

JavaScript事件代理(事件委託)

01揹包問題回溯法Java實現

其實回溯法實現01揹包問題很簡單,沒有網上說的那麼複雜,簡單概括來說就是每次進行搜尋如果搜尋到葉子節點且符合條件就儲存這個值,如果不符合條件就回溯,返回到上一層的揹包的容量和所裝入的物品價值,這樣遇到不符合條件就回溯直到搜尋完整個樹,最優結果就出來了
程式碼如下

public class BackTrackingKnapsack01Test {
    public int []weight;
    public int []value;
    public int MaxWeight;
    int count;
    int []take; //用來標記路徑
    int
[]BestChoice; int curValue=0; int curWeight=0; int bestValue=0; public void init(int []weight,int []value,int MaxWeight){ this.weight = weight; this.value = value; this.MaxWeight = MaxWeight; count = value.length; BestChoice = new int[count]; take =
new int[count]; if (weight==null||weight.length==0|| value==null||value.length==0|| weight.length!=value.length||MaxWeight<0){ System.out.println("引數出現錯誤"); return; } } public int[] find(int level){ if
(level > count-1){ if (curValue>bestValue){ bestValue = curValue; for (int i=0; i<take.length; i++){ BestChoice[i] = take[i]; } } }else { for (int i=0; i<2; i++){ take[level] = i; if (i==0){ find(level+1); }else{ if (curWeight+weight[level]<=MaxWeight){ curWeight+=weight[level]; curValue+=value[level]; find(level+1); //回溯 curWeight-=weight[level]; curValue-=value[level]; } } } } return BestChoice; } public static void main(String[] args) { BackTrackingKnapsack01Test B01Test = new BackTrackingKnapsack01Test(); B01Test.init(new int[]{16, 15, 15},new int[]{44,25,20},30); int[] result = B01Test.find(0); System.out.print("最佳選擇為:["); for (int i=0; i<result.length;i++){ if (i==result.length-1){ System.out.print(result[i]+"]"); }else { System.out.print(result[i]+","); } } System.out.print("\n此時價值最大,即"+B01Test.bestValue); } }

執行結果:
在這裡插入圖片描述