給定一個非負(fù)整數(shù) numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數(shù)是它左上方和右上方的數(shù)的和。
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/pascals-triangle
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
解題思路及方法
經(jīng)典,不多逼逼
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
// List<Integer>類存儲每行的值
List<Integer> row = new ArrayList<>();
for (int j = 0; j <= i; j++) {
// 邊界值賦1
if (j == 0 || j == i) {
row.add(1);
} else {
row.add(list.get(i - 1).get(j - 1) + list.get(i - 1).get(j));
}
}
list.add(row);
}
return list;
}
}
結(jié)果如下:
