【问题标题】:What would be the time complexity of the pascal triangle algorithm帕斯卡三角算法的时间复杂度是多少
【发布时间】:2015-09-10 09:56:38
【问题描述】:

负责解决如下问题(帕斯卡三角形),如下所示。

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

我已经成功实现了代码(见下文),但我很难弄清楚这个解决方案的时间复杂度是多少。列表的操作数是 1 + 2 + 3 + 4 + .... + n 操作数会减少到 n^2 数学如何工作并转换为 Big-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;
    }
}

【问题讨论】:

    标签: java algorithm performance time-complexity


    【解决方案1】:

    复杂度为O(n^2)

    代码中元素的每次计算都是在恒定时间内完成的。 ArrayList 访问是常数时间操作,以及插入,摊销常数时间。 Source:

    size、isEmpty、get、set、iterator 和 listIterator 操作运行 在恒定时间内。加法操作在摊销的常数时间内运行

    你的三角形有1 + 2 + ... + n 元素。这是arithmetic progression,总和为n*(n+1)/2,在O(n^2)

    【讨论】:

    • 感谢您的确认非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多