给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。在杨辉三角中,每个数是它左上方和右上方的数的和。
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
一、初解思路
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> data = new ArrayList<List<Integer>>();
if(numRows == 0) {
return data;
}
for(int i = 0; i < numRows ; i++) {
ArrayList<Integer> rowData = new ArrayList<Integer>();
for(int j = 0; j< i +1; j++) {
if(j == 0) {
rowData.add(1);
} else if (j == i) {
rowData.add(1);
} else if (i != 0){
rowData.add(data.get(i -1).get(j-1) + data.get(i-1).get(j));
}
}
data.add(rowData);
}
return data;
}
}
空间和时间复杂度O(numRows2)