-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPascalsTriangle.java
More file actions
42 lines (33 loc) · 976 Bytes
/
PascalsTriangle.java
File metadata and controls
42 lines (33 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package dynamic_programming;
import java.util.ArrayList;
import java.util.List;
/**
* Description: https://leetcode.com/problems/pascals-triangle
* Difficulty: Easy
* Time complexity: O(n^2)
* Space complexity: O(n^2)
*/
public class PascalsTriangle {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
result.add(List.of(1));
for (int i = 1; i < numRows; i++) {
List<Integer> row = buildRow(i + 1, result.get(i - 1));
result.add(row);
}
return result;
}
private List<Integer> buildRow(int size, List<Integer> prevRow) {
List<Integer> row = new ArrayList<>();
row.add(1);
int left = 0;
int right = 1;
for (int i = 1; i < size - 1; i++) {
row.add(prevRow.get(left) + prevRow.get(right));
left++;
right++;
}
row.add(1);
return row;
}
}