为什么以下c ++代码的时间复杂度为O(n ^ n)?

时间:2020-01-18 02:32:13

标签: algorithm time-complexity

这是此lettcode问题的https://leetcode.com/articles/best-time-to-buy-and-sell-stock-ii/的蛮力解决方案,我不明白为什么如果要求O(n ^ n),那么时间复杂性。谁能解释一下,并引导我完成,谢谢!

class Solution {
    public int maxProfit(int[] prices) {
        return calculate(prices, 0);
    }

    public int calculate(int prices[], int s) {
        if (s >= prices.length)
            return 0;
        int max = 0;
        for (int start = s; start < prices.length; start++) {
            int maxprofit = 0;
            for (int i = start + 1; i < prices.length; i++) {
                if (prices[start] < prices[i]) {
                    int profit = calculate(prices, i + 1) + prices[i] - prices[start];
                    if (profit > maxprofit)
                        maxprofit = profit;
                }
            }
            if (maxprofit > max)
                max = maxprofit;
        }
        return max;
    }
}

1 个答案:

答案 0 :(得分:0)

由于最内层的循环中有一个递归调用,因此扩展树如下图所示

                                        0
                ---------------------------------------------------------
                1                               2   ..                  n
    ------------------------            ---------------------          
    2           3  ..      n            3           4   ..  n   
----------  -------------       ----------   ------------
3   4 .. n  4   5  ..   n       4   5 .. n   5  6   ..  n
                                       ...

第一行进行n-1O(n)操作,第二行进行(n-1)+(n-2)+...+1 = n*(n-1)/2O(n^2)操作。同样,第三行上有O(n^3)个操作。树的高度/深度为n。因此,继续这种方式将有O(n^n)总计操作。