118. 楊輝三角 - 力扣(LeetCode) (leetcode-cn.com)
難度:簡單
題目描述:給定一個非負整數(shù) numRows聪轿,生成「楊輝三角」的前 numRows 行金赦。
在「楊輝三角」中外莲,每個數(shù)是它左上方和右上方的數(shù)的和。
Leetcode118.gif
分析
楊輝三角近似看成如下所示的例圖:
*
* *
* * *
所以楊輝三角可以表示為:
1
1 1
1 2 1
設(shè)置兩個指針一個為行指針(row)乏奥,一個為列指針(column)
楊輝三角中的元素可以分為兩種情況:
1- 當column==0或column==row時,值為1
2- 當為其他情況時亥曹,array[row][column] = array[row-1][column-1] + array[row-1][column]
解題
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> currentList = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (i == j || j == 0) {
currentList.add(1);
} else {
currentList.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
}
}
result.add(currentList);
}
return result;
}
}