2
我完成作業,其規格要求:遞歸裝箱算法不能擴展
- 遞歸解決方案
- 容量< = 100
- values.length < = 25
- 參數只有能力和索引
- 允許重複值
我已經花了數小時閱讀垃圾箱包裝和揹包問題。
以下工作但效率非常低。我得到了一堆有十幾個值的堆棧溢出。非常低效,不擴展,我不知道從哪裏開始。
建議將不勝感激。是的,這是一個學術任務,但我寧願排出來的問題,而不是乾脆放棄,賺取B.
public void calculateCombinations(int capacity, int index) {
count++;
if(index < values.length) {
if(values[index] <= capacity) {
currentSolution.addLast(index);
if(values[index] == capacity)
flushSolution();
else
capacity -= values[index];
}
calculateCombinations(capacity, index + 1);
} else
if(currentSolution.peekLast() != null)
calculateCombinations(capacity + values[currentSolution.peekLast()], currentSolution.removeLast() + 1);
}
我建議閱讀關於動態編程和記憶 – yurib 2013-02-25 21:22:08