【发布时间】:2020-08-14 13:54:11
【问题描述】:
我想知道为什么当我将 n - 1 更改为 --n 时,函数会抛出异常。 据我了解, --n 和 n - 1 产生相同的结果。请参阅打印()。请帮忙。谢谢。
private static void Print(int n)
{
if (n == 0) return;
Console.Write($"[{n}] -> ");
// regardless of --n or n--, the results are the same.
Print(n - 1);
}
private static double KnapSack(int maxWeight, Product[] products)
{
double maxValue = KnapSack(maxWeight, products, products.Length);
Console.WriteLine($"The max value the knapsack can hold is: {maxValue:C2}");
return maxValue;
}
private static double KnapSack(int maxWeight, Product[] products, int n)
{
if (n == 0 || maxWeight == 0)
return 0;
if (products[n - 1].Weight > maxWeight)
return KnapSack(maxWeight, products, n - 1);
else return Max
(
// if we change n - 1 to --n, it will throw an exception.
products[n - 1].Price + KnapSack(maxWeight - products[n - 1].Weight, products, n - 1),
KnapSack(maxWeight, products, n - 1)
);
}
【问题讨论】:
-
--n更改n。n-1只是计算一个新值,但不将其存储在n中。
标签: c# recursion dynamic-programming knapsack-problem