帕斯卡三角形算法的时间复杂度是多少?

11

负责解决以下问题(帕斯卡三角形),它看起来像这样。

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

我已经成功实现了下面的代码,但是我很难弄清楚这种解决方案的时间复杂度会是多少。对于列表的操作次数为 1 + 2 + 3 + 4 + .... + n,这个操作数量是否会减少到 n^2,并且这个数学计算如何转化为大O符号表示法?

我认为这类似于高斯公式n(n+1)/2,所以是O(n^2),但我可能错了,非常感谢任何帮助。

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        if(numRows < 1) return new ArrayList<List<Integer>>();;
        List<List<Integer>> pyramidVal = new ArrayList<List<Integer>>();

        for(int i = 0; i < numRows; i++){
            List<Integer> tempList = new ArrayList<Integer>();
            tempList.add(1);
            for(int j = 1; j < i; j++){
                tempList.add(pyramidVal.get(i - 1).get(j) + pyramidVal.get(i - 1).get(j -1));
            }
            if(i > 0) tempList.add(1);
            pyramidVal.add(tempList);
        }
        return pyramidVal;
    }
}
1个回答

17

复杂度为O(n^2)

您代码中每个元素的计算都是在常数时间内完成的。 ArrayList 访问是常数时间操作,插入是平摊常数时间。 来源:

大小,isEmpty,get,set,迭代器和listIterator 操作都在常数时间内运行。添加操作在平摊常数时间内运行

您的三角形有1 + 2 + ... + n 个元素。 这是一个等差数列求和,总和为n*(n+1)/2,属于O(n^2)


感谢确认,非常感激。 - Marquis Blount

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接