Algorithm 为什么以下c++;代码是O(n^n)?

Algorithm 为什么以下c++;代码是O(n^n)?,algorithm,time-complexity,Algorithm,Time Complexity,这是lettcode问题的强力解决方案:,我不明白为什么时间复杂度是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)

这是lettcode问题的强力解决方案:,我不明白为什么时间复杂度是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;
    }
}
类解决方案{
公共整数最大利润(整数[]价格){
返回计算(价格,0);
}
公共整数计算(整数价格[],整数s){
如果(s>=价格.长度)
返回0;
int max=0;
对于(int start=s;start最大利润)
最大利润=利润;
}
}
如果(最大利润>最大利润)
最大=最大利润;
}
返回最大值;
}
}

由于在最里面的循环中有一个递归调用,扩展树如下所示

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

第一行有
n-1
O(n)
操作,第二行有
(n-1)+(n-2)+…+1=n*(n-1)/2
O(n^2)
操作。类似地,在第三行上有
O(n^3)
操作。树的高度/深度为
n
。因此,继续这种方式将有
O(n^n)
总操作。

因为在最里面的循环中有一个递归调用,所以扩展树如下所示

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

第一行有
n-1
O(n)
操作,第二行有
(n-1)+(n-2)+…+1=n*(n-1)/2
O(n^2)
操作。类似地,在第三行上有
O(n^3)
操作。树的高度/深度为
n
。因此,继续这种方式将有
O(n^n)
总操作。

这是一个很好的解释,我没有意识到扩展树应该用于分析递归。谢谢这是一个很好的解释,我没有意识到应该用扩展树来分析递归。谢谢