題目
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行,

在楊輝三角中,每個數是它左上方和右上方的數的和,
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/pascals-triangle
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
題解
class Solution {
public List<List<Integer>> generate(int numRows) {
// 創建回傳容器
List<List<Integer>> list = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; i++) {
// 創建行容器
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= i; j++) {
// 判斷是否為邊界
if (j == 0 || j == i) {
// 邊界值為1
row.add(1);
} else {
// 找尋左上與右上
row.add(list.get(i-1).get(j-1) + list.get(i-1).get(j));
}
}
list.add(row);
}
return list;
}
}
0ms 36.2MB
判斷是否為邊界,是邊界則值為1,不是邊界的話,則找向上一個陣列的即可
更多題解點擊此處
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230981.html
標籤:java
上一篇:小名的開源專案【EamonVenti】0.0篇 —— 學習如何搭建一個簡單的SpringCloud架構,體驗微服務的強大!
