递归中使用的前缀递减与减法



我想知道为什么当我将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)
);
}

如果您更改了所有3,那么每次它都会一次又一次地递减。所以它变成n-1、n-2和n-3。

换言之,n-1不会突变n。但是——n会。

最新更新