Leetcode(118) Pascal Triangle

Description

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

img
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

1
2
3
4
5
6
7
8
9
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

解法

找到计算公式即可:

1
2
3
4
if j == 0 or i == j:
A[i][j] = 1
else:
A[i][j] = A[i-1][j-1] + A[i-1][j]

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i = 0;i < numRows; i++){
List<Integer> tmpRow = new ArrayList<Integer>();
tmpRow.add(1);
for(int j = 1;j < i;j++){
tmpRow.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
}
if(i >= 1){
tmpRow.add(1);
}
res.add(tmpRow);
}
return res;
}
}