简体   繁体   English

Pascal三角算法分析

[英]Pascal's Triangle Algorithm Analysis

Do you think the pseudocode below is correct for calculating pascal's triangle? 您认为下面的伪代码对计算帕斯卡的三角形是正确的吗? What would its time and space complexity be like? 它的时间和空间复杂度如何? and how can I calculate it? 以及如何计算呢?

pascal triangle(n){
    list<list<int>> triangle // double list saving the triangle




    triangle.get(0).add(1)
    for(int i=1; i<n; i++){
        for(int j=0; j<i; j++){
            if(triangle.get(i-1).get(j)==null || triangle.get(i-1).get(j-1)==null)  
                triangle.get(i).add(1)
            else
                triangle.get(i-1).add(triangle.get(i-1).get(j)+triangle.get(i-1).get(j-1))

        }

    }

    print(triangle)
}

Your pseudocode looks like it makes sense. 您的伪代码看起来很有意义。

For the complexity 对于复杂性

Your algorithm is trying to calculate each number of the triangle once. 您的算法尝试计算一次三角形的每个数。 If we let each calculation be constant time complexity then we are doing: 如果让每个计算成为恒定的时间复杂度,那么我们正在做:

sum(i) (0 -> n)

Please excuse the poor notation To clarify: 请原谅可怜的符号 以澄清:

If n is 6 then we are going to iterate 6 + 5 + 4 + 3 + 2 + 1 times. 如果n6,那么我们将迭代6 + 5 + 4 + 3 + 2 + 1次。 This actual complexity can be simplified to: 这种实际的复杂性可以简化为:

(n + 1) * (n/2)

effectively 有效

O(n^2)

Another way of looking at the complexity 另一种看待复杂性的方法

You are essentially doing the area of a triangle in iterations which is b*h/2 . 您实际上是在迭代中做一个三角形的面积,即b*h/2 Well we know the height of Pascal's triangle to be n . 我们知道Pascal三角形的高度为n The bottom of the triangle (or the base) has n numbers. 三角形的底部(或底部)有n个数字。 Therefore, we are generating: 因此,我们正在生成:

n^2/2

which has a complexity of O(n^2) 复杂度为O(n ^ 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM