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

问题描述 投票:0回答:1

我想知道为什么当我把n - 1改成--n时,函数会抛出一个异常.根据我的理解,--n和n - 1产生的结果是一样的。请看Print()。请帮助我。谢谢你的帮助。

    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)
        );
    }
c# recursion dynamic-programming knapsack-problem
1个回答
2
投票

如果你把这3个都改了,那么每次都是一减再减。所以就变成了n-1、n-2和n-3。

换句话说,n-1不会使n变异,但--n会。

© www.soinside.com 2019 - 2024. All rights reserved.