zoukankan      html  css  js  c++  java
  • leetcode 精选top面试题

    118. 杨辉三角

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和

    示例:

    输入: 5
    输出:
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    思路:

    杨辉三角,知道上一行就可以求出下一行,但是注意每行的首尾元素都是1,需要单独添加

     1 class Solution {
     2     public List<List<Integer>> generate(int numRows) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         if(numRows <= 0){
     5             return res;
     6         }
     7         List<Integer> temp = new ArrayList<Integer>();
     8         temp.add(1);
     9 
    10         res.add(temp);
    11         for(int i = 1; i < numRows; i++){
    12             List<Integer> nextRowList = new ArrayList<Integer>();
    13             nextRowList.add(1);
    14             for(int j = 0; j < temp.size() - 1; j++){
    15                 // 遍历上一行的每个元素,生成一个新元素添加到nextRowList中    
    16                 nextRowList.add(temp.get(j) + temp.get(j + 1));
    17             }
    18             nextRowList.add(1);
    19             res.add(new ArrayList<Integer>(nextRowList));
    20             temp = nextRowList;     // 更新temp
    21         }
    22         return res;
    23     }
    24 }
    leetcode 执行用时:1 ms, 在所有 Java 提交中击败了66.94%的用户
    内存消耗:36.2 MB, 在所有 Java 提交中击败了80.37%的用户

    复杂度分析:

    时间复杂度:O(n2)。双重循环,但是内层循环的迭代次数分别是1, 2, 3,.., n; 所以时间复杂度为O(1 + 2 + 3 + n) = O((n2+n)/2), 所以时间复杂度为O(n2)。
    空间复杂度:O(n)。如果不考虑存储结果的列表集合,算法需要一个存放上一行的结果的列表,但是这个列表在使用完之后就会被回收,所以只需要计算一次,则空间复杂度为O(n)。
  • 相关阅读:
    Codeforces Round #592 (Div. 2)
    2019 China Collegiate Programming Contest Qinhuangdao Onsite
    2019CCPC 秦皇岛 E.Escape
    2018 Multi-University Training Contest 3
    AtCoder Regular Contest 098
    Educational Codeforces Round 74 (Rated for Div. 2)
    Codeforces Round #590 (Div. 3) F
    AtCoder Regular Contest 99
    [AH2017/HNOI2017] 单旋
    [CF1304F] Animal Observation
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/13978672.html
Copyright © 2011-2022 走看看