给定一个非负整数 numRows
,生成「杨辉三角」的前 numRows
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
代码:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> resultLists = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> colList = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
colList.add(1);
}else {
// 获取上面两个元素和
colList.add(resultLists.get(i-1).get(j-1)+resultLists.get(i-1).get(j));
}
}
resultLists.add(colList);
}
return resultLists;
}
}