问题描述
代码是针对0/1背包问题的递归动态编程。
因此,让我首先说一下代码看起来是正确的,因为当我运行它时,它会显示结果,但是仅当我取消对printf
行的注释(请参阅突出显示的部分)并且与解决方案无关时(我仅用于测试目的),我觉得这很奇怪。有人可以告诉我为什么会这样吗。
int main() {
int DP_Recursive(int W,static int wt[],static int val[],int n,static int dp[][]);
static int wt[5] = { 5,10,20,30 };
static int val[5] = { 50,60,100,120 };
static int dp[5][60]; //marker 2-D array
for (int i = 0; i <= 5; i++) {
for (int w = 0; w <= 50; w++) {
dp[i][w] = -1;
}
}
printf("The total loot is %d$.",DP_Recursive(50,wt,val,2,dp));
}
//Recursive D.P. solution
int DP_Recursive(int W,static int dp[5][60]) {
//-------**HIGHLIGHTED PART**-----------
printf("%d",dp[2][30]);
//--------------------------
//Base case
if (n == 0 || W == 0)
return 0;
if (dp[n][W] != -1)
return dp[n][W];
if (wt[n-1] > W) {
dp[n][W] = DP_Recursive(W,n - 1,dp);
return dp[n][W];
} else {
dp[n][W] = max(val[n-1] + DP_Recursive(W - wt[n-1],n-1,dp),DP_Recursive(W,dp));
}
return dp[n][W];
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)