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

前端之家收集整理的这篇文章主要介绍了java – pascal三角形算法的时间复杂度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
负责解决以下问题(Pascal Triangle),看起来像这样.
  1. [
  2. [1],[1,1],2,3,4,6,1]
  3. ]

我已经成功实现了代码(见下文),但我很难搞清楚这个解决方案的时间复杂度.列表的操作次数是1 2 3 4 …. n操作次数减少到n ^ 2数学如何工作并转换为Big-O表示法?

我认为这类似于高斯公式n(n 1)/ 2所以O(n ^ 2)但我可能是错的任何帮助非常感谢

  1. public class Solution {
  2. public List<List<Integer>> generate(int numRows) {
  3. if(numRows < 1) return new ArrayList<List<Integer>>();;
  4. List<List<Integer>> pyramidVal = new ArrayList<List<Integer>>();
  5.  
  6. for(int i = 0; i < numRows; i++){
  7. List<Integer> tempList = new ArrayList<Integer>();
  8. tempList.add(1);
  9. for(int j = 1; j < i; j++){
  10. tempList.add(pyramidVal.get(i - 1).get(j) + pyramidVal.get(i - 1).get(j -1));
  11. }
  12. if(i > 0) tempList.add(1);
  13. pyramidVal.add(tempList);
  14. }
  15. return pyramidVal;
  16. }
  17. }

解决方法

复杂度是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)

猜你在找的Java相关文章