118. 杨辉三角
给定一个非负整数 *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
二、方法一
根据我们所学的数学,可以得到规律,除了开头和结尾,剩下的数均等于上一行的左列和上一行的当前列的和
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> row = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
row.add(1);
} else {
row.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
}
}
res.add(row);
}
return res;
}
}
复杂度分析
- 时间复杂度:O(numRows ^2)。
- 空间复杂度:O(1)。不考虑返回值的空间占用。