最近,我试图研究和实现背包问题(我之前几年学习过)。所以我可以理解并且有最佳解决方案的想法,比如背包值是100,并且有一定的权重如40,60,100。那么最佳解决方案将是100或者相当于背包价值。我停留在编程的一部分中,无法弄清楚这是如何实际工作的,尽管使用教程进行递归尝试。让我注释掉,我已经明白:背包 - 编程时无法理解部分
/*A function or method to determine the max number*/
int max(int a, int b)
{
return (a > b) ? a : b;
}
/*Knapsack function or method with parameters knapsack value - w, weights, amounts, number of elements*/
int Knapsack(int w, int weight[], int amt[], int n)
{
if(n == 0 || w == 0)
{
return 0;
}
if(weight[n - 1] > w) /*If the nth value is greater than the knapsack value, then there will no optimal solution*/
{
return Knapsack(w, weight, amt, n - 1);
}
else
{
return max(amt[n - 1] + Knapsack(w - weight[n - 1], weight, amt, n - 1), Knapsack(w, weight, amt, n - 1)); /*Stuck in this section - It returns perfect solution but unable to understand how it's working. Debugged not getting the answer as expected*/
}
}
int main(void)
{
int amt[3], weight[3], w, i, elements, n;
/*printf("Enter number of elements: ");
scanf("%d", &elements);*/
printf("Enter the weight and amount individually up to 3: ");
for(i = 0; i < 3; i++)
{
scanf("%d %d", &weight[i], &amt[i]);
}
printf("\nEnter the knapsack value: ");
scanf("%d", &w);
n = sizeof(amt)/sizeof(amt[0]);
printf("%d %d", Knapsack(w, weight, amt, n), n);
return 0;
}
如果有人有时间简要的工作过程中,我无法理解编程来解释我将不胜感激。甚至尝试使用它的动态编程。但它似乎安静复杂。这是一个完美的解决方案,研究背包问题:
请问这个问题属于[Codereview?](http://codereview.stackexchange.com/) –
@WeatherVane没有,因为它要求解释一个给定的代码如何工作,而不是要求审查他们的论坛自己的代码。 –