leetcode 118. pascal’s triangle

118. Pascal’s Triangle

Difficulty: Easy

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


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]
]

Solution

Language: Java

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