【LeetCode】每日一題118. 楊輝三角
阿新 • • 發佈:2020-12-07
118. 楊輝三角
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
方法一:
題沒啥難度,按照條件構造就行了~
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> curr;
List<Integer> pre = null;
for (int i = 0; i < numRows; i++) {
curr = new ArrayList<>();
if (i > 0) {
pre = ans.get(i - 1);
}
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
curr.add(1);
} else {
curr.add(pre.get(j - 1) + pre.get(j));
}
}
ans.add(curr);
}
return ans;
}