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. Set接口——LinkedHashSet集合

    底层是由哈希表+链表:

  2. 配置开发环境2——eclipse配置

    纯手动配置eclipse, Eclipse配置 配置工作空间的编码方式 General—Workspace:改成Other:UTF-8 配置property的编码方式 配置maven Window — ...

  3. bzoj4358 premu

    题目链接 莫队算法 没有用线段树,而是看了showson的并查集%%% #include<algorithm> #include<iostream> #include<c ...

  4. read 命令详解

    read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量 语法选项 -p read –p “提示语句”,则屏幕就会输出提示语句,等待输入,并将输入存储在REPLY中 -n ...

  5. Deprecated: getEntityManager is deprecated since Symfony 2.1

    PHP5.3应用中,登陆后台管理时提示错误: Deprecated: getEntityManager is deprecated since Symfony 2.1. Use getManager  ...

  6. springboot打包部署到tomcat

    一. springboot打成war包: 1. 首先查看是否为war 2. File----->ProjectStruture,选择Artifacts,中部点击“+”号 3. 按图中标记进行选择 ...

  7. 高级架构进阶之HashMap源码就该这么学

    引言--面试常见的问题 问:“你用过HashMap,你能跟我说说它吗?” “当然用过,HashMap是一种<key,value>的存储结构,能够快速将key的数据put方式存储起来,然后很 ...

  8. 使用Holer外网SSH访问内网(局域网)Linux系统

    1. Holer工具简介 Holer exposes local servers behind NATs and firewalls to the public internet over secur ...

  9. usb帧格式

    源: usb帧格式

  10. HTML <​canvas> testing with Selenium and OpenCV

    from: https://www.linkedin.com/pulse/html-canvas-testing-selenium-opencv-maciej-kusz Since HTML < ...