博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
119. Pascal's Triangle II - Easy
阅读量:7224 次
发布时间:2019-06-29

本文共 1253 字,大约阅读时间需要 4 分钟。

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

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

Example:

Input: 3Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

 

brute force,同Pascal's Triangle,https://www.cnblogs.com/fatttcat/p/10054249.html

注意这题的下标和上题不同,这里的input rowIndex = 5 返回的是原数组中的第5行,即下标为4对应的数组。

Input: 5Output:[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]

因此外层循环应该从0 ~ rowIndex + 1

另外还要注意!由于从始至终只用了一个arraylist,在设第一个元素为1的时候,不能只用list.add(1),而应该用list.add(0, 1),否则会在list后追加1,而不是在index=0的位置加1

e.g. rowIndex = 3

i = 0   res = 1

i = 1    res = 1 1
i = 2   res = 1 1 1 -> 1 2 1
i = 3   res = 1 1 2 1 -> 1 3 2 1 -> 1 3 3 1

时间:O(N^2),空间:O(K)

class Solution {    public List
getRow(int rowIndex) { List
res = new ArrayList<>(); if(rowIndex < 0) return res; for(int i = 0; i < rowIndex + 1; i++) { res.add(0, 1); for(int j = 1; j < res.size() - 1; j++) res.set(j, res.get(j) + res.get(j + 1)); } return res; }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10054504.html

你可能感兴趣的文章
Spring 注解<context:annotation-config> 和 <context:component-scan>的作用与区别
查看>>
混合开发 Hybird Cordova PhoneGap web 跨平台 MD
查看>>
高效沟通的秘籍-沟通视窗
查看>>
怎么创建SpringBoot项目
查看>>
RabbitMQ 延迟队列实现订单支付结果异步阶梯性通知
查看>>
基于Elastalert的安全告警剖析
查看>>
SQL中ON和WHERE的区别
查看>>
art.template 循环里面分组。
查看>>
[Algorithms] Solve Complex Problems in JavaScript with Dynamic Programming
查看>>
MetaModelEngine:约束和验证
查看>>
垂直居中层 js操作css
查看>>
c_str 以及atoi
查看>>
Wrox红皮书上市十周年 惊喜馈赠读者
查看>>
ASP.NET运行时错误
查看>>
acdream 1014 Dice Dice Dice(组合)
查看>>
(DT系列六)devicetree中数据和 struct device有什么关系
查看>>
javascript异步编程系列【七】----扫盲,我们为什么要用Jscex
查看>>
.N“.NET研究”ET中的异步编程(二)- 传统的异步编程
查看>>
C#汉字转拼音代码分享|建议收藏
查看>>
WindowsServer2003+IIS6+ASP+NET+PHP+MSSQL+MYSQL配置说明 |备份于waw.cnblogs.com
查看>>