簡體   English   中英

帕斯卡三角算法的時間復雜度是多少?

[英]What would be the time complexity of the pascal triangle algorithm

負責解決以下問題(Pascal Triangle),看起來像這樣。

[
     [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;
    }
}

復雜度是O(n^2)

代碼中每個元素的計算都是在恆定時間內完成的。 ArrayList訪問是常量時間操作,也是插入,分攤的常量時間。 來源

size,isEmpty,get,set,iterator和listIterator操作以恆定時間運行。 添加操作以分攤的常量時間運行

你的三角形有1 + 2 + ... + n元素。 這是算術級數 ,總和為n*(n+1)/2 ,其為O(n^2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM