给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
提示:
1 <= numRows <= 30
Related Topics
数组
动态规划
方法一:双重for循环
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
res.add(Arrays.asList(1));
for (int i = 1; i < numRows; i++) {
List<Integer> preList = res.get(i - 1);
List<Integer> list = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
list.add(1);
} else {
list.add(preList.get(j - 1) + preList.get(j));
}
}
res.add(list);
}
return res;
}
}