题目
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路
- 创建一个二维数组,每一层的计算结果存储在二位数组中
- 将二维数组添加到一个list中
java
class Solution {
public List<List<Integer>> generate(int numRows) {
ArrayList<List<Integer>> res = new ArrayList<>();
int[][] a = new int[numRows][numRows];
for(int i = 0; i < numRows; i++){
ArrayList<Integer> list = new ArrayList<>();
for(int j = 0; j < i + 1; j++){
if(j == 0 || j == i){
a[i][j] = 1;
}else{
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
list.add(a[i][j]);
}
res.add(list);
}
return res;
}
}