我想解决背包问题的一个变种,并为它写了一个递归解决方案。但我的解决方案正在返回一个错误的值。我想我的算法是有缺陷的。你能帮我找到故障吗?动态规划递归给出了错误的结果
这是我的代码。
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发现的基本骨架。这算法有缺陷还是我误解了它。
感谢
奇丹巴拉姆