Leetcode118_Pascal's Triangle_Easy
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.
思路不难理解,但细节多。 注意:
- ArrayList 和 Array的不同: https://www.geeksforgeeks.org/array-vs-arraylist-in-java/ (一定要看!)
- 对于每一行,不要忘了先创建一个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的更多相关文章
随机推荐
- limit小结
1. Limit接受一个或两个数字参数.参数必须是一个整数常量.如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目. 2. 初始记录行的偏移量是 0(而不是 ...
- Linux服务器---流量监控ntop
Ntop Ntop 是一款类似于sniffer的流量监控工具,它显示出的流量信息比mrtg更加详细. 1 .安装一些依赖软件 [root@localhost bandwidthd]# yum ins ...
- mac电脑设置USB键盘按键方法,设置多显示屏镜像显示器的方法
mac电脑设置USB键盘按键方法,设置多显示屏镜像显示器的方法 设置多显示屏镜像显示器的方法 ==================== mac电脑复制粘贴使用command+c command+v - ...
- 算法训练 P0505
一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积.阶乘的增长速度非常快,例如,13!就已经比较大了,已经无法存放在一个整型变量中:而35!就更大了,它已经无法存放在一个浮点型变量中.因此, ...
- Codeforces 456A - Laptops
题目链接:http://codeforces.com/problemset/problem/456/A One day Dima and Alex had an argument about the ...
- [转载] Oracle之内存结构(SGA、PGA)
2011-05-10 14:57:53 分类: Linux 一.内存结构 SGA(System Global Area):由所有服务进程和后台进程共享: PGA(Program Global Area ...
- 记账本微信小程序开发三
一.制作登陆界面: 更改全局配置,改颜色,名称: 界面 格式 登录界面 二.页面的跳转 按钮的设置 注册事件 结果
- input file accept类型
Valid Accept Types: For CSV files (.csv), use: <input type="file" accept=".csv&quo ...
- jsoi r2d1t3的50分
#include<bits/stdc++.h> using namespace std; int n,r,x,y; double ans; double dis(int x,int y){ ...
- v-on事件绑定指令
v-on:事件绑定 v-on简写:@ 绑定click事件时: 代码: <script> window.onload= () =>{ let vm=new Vue({ el:'#two ...