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]]
解法(数学)
class Solution {
public List<List<Integer>> generate(int numRows) {
//在list中再创建一个list
List<List<Integer>> res = new ArrayList<>();
//定义一个二维数组arr
int[][] arr = new int[numRows][numRows];
for(int i = 0;i < numRows;i++){
List<Integer> list = new ArrayList<Integer>();
for(int j = 0;j <= i;j++){
//令杨辉三角的首尾都为1
if(j == 0 || i == j){
arr[i][j] = 1;
}else{
//杨辉三角:即第 n 行的第 i 个数等于第 1n−1 行的第 i−1个数和第 i 个数之和
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
list.add(arr[i][j]);
}
res.add(list);
}
return res;
}
}