又一个背包问题......我理解背包问题的概念,但我的部分代码有问题......我想相信我正朝着正确的方向前进,但也许不是?
Let's say I have a list of 1,2,3,6,7 and my goal weight is 4:
The items that will equal this weight are 1 and 3.
My first iteration will go like this:
Item: 1
Goal Weight: 3 (I did weight - the item)
Items: 1,2
Goal Weight: 1
Items: 1,2,3
Goal Weight: -2
-- Once the weight reaches < 0, it should restart the goal weight and then restart the position
but the items should start at 1 and skip over 2, going straight to 3. An Example below:
Items: 1
Goal Weight: 3
Items: 1, 3
Goal Weight: 0 // Finished
--但是,我不知道如何跳过 2 并转到 3。在某种程度上,我理解这个问题使用组合/排列。我只是无法让我的代码按照我想要的方式工作。下面是我的代码。如果我有任何不清楚的地方,请告诉我。
public boolean recursive(int weight, int start){
if(weight == 0){// if weight is zero, we found what we wanted.
System.out.println("We did it");
return true;
}
else if(weight < 0){ //Too much weight in the bag.
if(start == storeItems.length-1){ //reached the end of the array.
recursive(goalWeight, start + 1);
return false;
}
else{ // did not reach end of the array but still not the right combination of numbers.
recursive(weight, start + 1);
}
}
else if(weight > 0){
System.out.println(storeItems[start]);
boolean x = recursive(weight - storeItems[start], start + 1);
}else{
System.out.print("No values");
}
return false;
}