微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – pascal三角形算法的时间复杂度

负责解决以下问题(Pascal Triangle),看起来像这样.
[
     [1],[1,1],2,3,4,6,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访问是常量时间操作,也是插入,分摊的常量时间. Source

The size,isEmpty,get,set,iterator,and listIterator operations run
in constant time. The add operation runs in amortized constant time

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

原文地址:https://www.jb51.cc/java/240003.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐