Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
] 思路:
数据结构的使用:List<List<Integer>>
对于初始化第一行。对于每一行,要把第一个元素和最后一个元素赋值为1; 行内剩余元素i通过访问上一行的i和i-1.
思路不难理解,但细节多。 注意:
  1. ArrayList 和 Array的不同: https://www.geeksforgeeks.org/array-vs-arraylist-in-java/ (一定要看!)
  2. 对于每一行,不要忘了先创建一个List(Line 9, 13, 14),才能对其操作,如添加元素
代码:
 class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>(); if (numRows == 0) {
return triangle;
} triangle.add(new ArrayList<>());
triangle.get(0).add(1); for (int rowNum = 1; rowNum < numRows; rowNum++){
List<Integer> row = new ArrayList<Integer>();
List<Integer> prevRow = triangle.get(rowNum - 1); row.add(1);
for(int j = 1; j < rowNum; j++){
row.add(prevRow.get(j-1) + prevRow.get(j));
}
row.add(1);
triangle.add(row);
} return triangle;
}
}

时间复杂度:O(numRows^2)

空间复杂度:O(numRows^2)

												

Leetcode118_Pascal's Triangle_Easy的更多相关文章

随机推荐

  1. 前端规范--eslint standard

    https://github.com/standard/standard/blob/master/docs/RULES-zhcn.md

  2. LoadRunner录制登录机票网址,并回放,加断言

    回放录制登录过程脚本,加断言 在页面登录的过程如下: 1先进入http://127.0.0.1:1080/WebTours/index.htm 2之后获取userSession信息 3在输入信息后点击 ...

  3. (Review cs231n) The Gradient Calculation of Neural Network

    前言:牵扯到较多的数学问题 原始的评分函数: 两层神经网络,经过一个激活函数: 如图所示,中间隐藏层的个数的各数为超参数: 和SVM,一个单独的线性分类器需要处理不同朝向的汽车,但是它并不能处理不同颜 ...

  4. AtCoder Beginner Contest 087 (ABC)

    A - Buying Sweets 题目链接:https://abc087.contest.atcoder.jp/tasks/abc087_a Time limit : 2sec / Memory l ...

  5. sparkStrming 实时插入 mysql 今天使用echart 实现了简单数据展示 很low 但学习必须加深

  6. 全球最大的3D数据集公开了!标记好的10800张全景图

    Middlebury数据集 http://vision.middlebury.edu/stereo/data/ KITTI数据集简介与使用 https://blog.csdn.net/solomon1 ...

  7. JAVA获取不同操作系统的分隔符等参数

    import java.util.Properties; public class SeparatorUtils { /* system properties to get separators */ ...

  8. Spring/SpringMVC/MyBatis(持久层、业务层、控制层思路小结)

    准备工作: ## 7 导入省市区数据到数据库中 1. 从FTP下载SQL脚本文件 2. 把脚本文件移动到易于描述绝对路径的位置 3. 进入MySQL控制台 4. 使用`xxx_xxx`数据库 5. 运 ...

  9. fjwc2019 D1T2 原样输出(后缀自动机+dp)

    #179. 「2019冬令营提高组」原样输出 暴力对每个串建后缀自动机,然后暴力枚举每个自动机的子串.可以拿到部分分. 然鹅我们可以把每个后缀自动机连起来. 我们知道,后缀自动机是用最少的点(空间)表 ...

  10. 运行android模拟器,emulator: ERROR: x86 emulation currently requires hardware acceleration!

    运行android模拟器,emulator: ERROR: x86 emulation currently requires hardware acceleration! 问题: 运行android模 ...