我想解決揹包問題的一個變種,併爲它寫了一個遞歸解決方案。但我的解決方案正在返回一個錯誤的值。我想我的算法是有缺陷的。你能幫我找到故障嗎?動態規劃遞歸給出了錯誤的結果
這是我的代碼。
int calc_budget(int b, int i){
// If we have reached the end
if(i >= nParty){
tbl[b][i] = 0;
return tbl[b][i];
}
//If remaining capacity is not able to hold the ith capacity, move on to next element
if(budget[i] > b){
if(tbl[b][i+1] == 0){
tbl[b][i+1] = calc_budget(b,i+1);
}
return tbl[b][i+1];
}
else{ //If the ith capacity can be accomodated
//Do not include this item
if(tbl[b][i+1] == 0){
tbl[b][i] = calc_budget(b,i+1);
}
// Include this item and consider the next item
if(tbl[b-budget[i]][i+1] == 0){
tbl[b-budget[i]][i] = fun[i] + calc_budget(b-budget[i], i+1);
}
// We have the results for includinng ith item as well as excluding ith item. Return the best (max here)
return max(tbl[b][i], tbl[b-budget[i]][i]);
}
}
Objective of the problem: To find the maximum fun by optimally using the given max budget
以下是我的輸入。
budget[3] = {19,12,19}
fun[3] = {2,4,5}
calc_budget(30,0)
allowed budget: 30
程序的正確答案應該是5.我正在返回7.我已經繪製了遞歸樹以嘗試調試。我的發現:在選擇項目0(右子樹)時,val = 2 +(11,1)。這(11,1)將導致最大((11,2)和0)。 (11,2)是5,所以最終結果是2 + 5 = 7。在這種DP技術中,我的算法不應該選擇11,2作爲預算總和超過給定的。但是這是我爲遞歸DP發現的基本骨架。這算法有缺陷還是我誤解了它。
感謝
奇丹巴拉姆