Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 89f0488

Browse files
Merge pull request MisterBooo#80 from xiaoshuai96/master
solved @xiaoshuai96
2 parents b396921 + 2a77708 commit 89f0488

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

‎0118-Generate/Animation/resource.gif‎

28.2 KB
Loading[フレーム]
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
2+
>
3+
> 个人博客:https://www.zhangxiaoshuai.fun
4+
5+
**本题选自leetcode第118题,easy级别,目前通过率66.4%**
6+
### 题目描述:
7+
```
8+
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
9+
示例:
10+
11+
输入: 5
12+
输出:
13+
[
14+
[1],
15+
[1,1],
16+
[1,2,1],
17+
[1,3,3,1],
18+
[1,4,6,4,1]
19+
]
20+
```
21+
22+
### 题目分析:
23+
初中时候学习的杨辉三角想不到又在这里出现了,题意很容易理解,每一行中的第一个数字和最后一个数字都是1,中间的数字都是通过上面相邻的两个数字相加得到。题目给我们一个杨辉三角的非负行数,然后我们生成对应的杨辉三角(集合)。
24+
既然返回的是一个List<List<Integer>>,那么我们用一个大集合来放置每一行的数,每一行的数我们分别用一个小集合来存放,最后将每一个小集合添加进大集合中。
25+
26+
### gif动画演示:
27+
28+
官方中已经有做的非常好的gif图解,这里直接展示:
29+
30+
![](../Animation/resource.gif)
31+
32+
### 代码:
33+
34+
```java
35+
public List<List<Integer>> generate(int numRows) {
36+
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
37+
//给定的numRows为0时直接返回空集合即可
38+
if (numRows == 0) {
39+
return triangle;
40+
}
41+
42+
//因为杨辉三角的第一行总是1,所以先新建一个list,并将1加入该list中
43+
triangle.add(new ArrayList<>());
44+
triangle.get(0).add(1);
45+
46+
//从第二行开始,新建表示当前行的list,拿到当前行的前一行的list
47+
for (int rowNum = 1; rowNum < numRows; rowNum++) {
48+
List<Integer> row = new ArrayList<>();
49+
List<Integer> prevRow = triangle.get(rowNum-1);
50+
51+
//一行中的第一个元素
52+
row.add(1);
53+
54+
//针对每一行,都是上一行的相邻的两个元素相加得到两个1中间的数
55+
for (int j = 1; j < rowNum; j++) {
56+
row.add(prevRow.get(j-1) + prevRow.get(j));
57+
}
58+
59+
//一行中的最后一个元素
60+
row.add(1);
61+
62+
//最后将"整行添加到大集合中"
63+
triangle.add(row);
64+
}
65+
return triangle;
66+
}
67+
```
68+
69+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /