Time complexity of Java Pascal triangle algorithm

Responsible for solving the following problems (Pascal triangle), which looks like this

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

I have successfully implemented the code (see below), but it is difficult for me to understand the time complexity of this solution The number of operations on the list is 1 2 3 4 How does mathematics work and convert to Big-O notation when the number of n operations is reduced to n ^ 2?

I think this is similar to Gauss formula n (n 1) / 2, so o (n ^ 2) but I may be wrong for any help. Thank you very much

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

Solution

The complexity is O (n ^ 2)

The calculation of each element in the code is completed in a constant time ArrayList access is not only a constant time operation, but also a constant time for insertion and allocation Source:

Your triangle has 1, 2... N elements This is arithmetic progression. The sum is n * (n 1) / 2, which is O (n ^ 2)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>