[英]What would be the time complexity of the pascal triangle algorithm
Tasked with solving the following problem (Pascal Triangle) which looks like this. 负责解决以下问题(Pascal Triangle),看起来像这样。
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
I've successfully implemented the code(see below) but I'm having a tough time figuring out what the time complexity would be for this solution. 我已经成功实现了代码(见下文),但我很难搞清楚这个解决方案的时间复杂度。 The number of operations by list is 1 + 2 + 3 + 4 + .... + n would number of operations reduce to n^2 how does the math work and translate into Big-O notation?
列表的操作次数是1 + 2 + 3 + 4 + .... + n操作次数减少到n ^ 2数学如何工作并转换为Big-O表示法?
I'm thinking this is similar to the gauss formula n(n+1)/2 so O(n^2) but I could be wrong any help is much appreciated 我认为这类似于高斯公式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;
}
}
Complexity is O(n^2)
. 复杂度是
O(n^2)
。
Each calculation of element in your code is done in constant time. 代码中每个元素的计算都是在恒定时间内完成的。 ArrayList accesses are constant time operations, as well as insertions, amortized constant time.
ArrayList访问是常量时间操作,也是插入,分摊的常量时间。 Source :
来源 :
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
size,isEmpty,get,set,iterator和listIterator操作以恒定时间运行。 The add operation runs in amortized constant time
添加操作以分摊的常量时间运行
Your triangle has 1 + 2 + ... + n
elements. 你的三角形有
1 + 2 + ... + n
元素。 This is arithmetic progression that sums to n*(n+1)/2
, which is in O(n^2)
这是算术级数 ,总和为
n*(n+1)/2
,其为O(n^2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.