LeetCode118-杨辉三角

题目链接

英文链接:https://leetcode.com/problems/pascals-triangle/

中文链接:https://leetcode-cn.com/problems/pascals-triangle/

题目详述

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

1
2
3
4
5
6
7
8
9
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

题目详解

  • 杨辉三角按照规则进行递推即可。
  • 把左边拉直,两边是 1,中间的数是它左上方的数与上方的数之和。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class LeetCode_00118 {

public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>(numRows);
for (int i = 0; i < numRows; ++i) {
List<Integer> list = new ArrayList<>(i + 1);
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i) {
list.add(1);
} else {
list.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
}
}
res.add(list);
}
return res;
}
}