-
Notifications
You must be signed in to change notification settings - Fork 2
/
PascalTriangle.java
47 lines (36 loc) · 1.16 KB
/
PascalTriangle.java
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
43
44
45
46
47
package leetcode.list;
import java.util.ArrayList;
import java.util.List;
public class PascalTriangle {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
result.add(new ArrayList<>());
for (int j = 0; j <= i; j++) {
int val = 1;
if (j != 0 && j != i) {
val = result.get(i - 1).get(j - 1)
+ result.get(i - 1).get(j);
}
result.get(i).add(val);
}
}
return result;
}
public List<Integer> getRow(int rowIndex) {
List<Integer> lastRow = new ArrayList<>();
List<Integer> thisRow = null;
for (int i = 0; i <= rowIndex; i++) {
lastRow = thisRow;
thisRow = new ArrayList<>();
for (int j = 0; j <= i; j++) {
int val = 1;
if (j != 0 && j != i) {
val = lastRow.get(j - 1) + lastRow.get(j);
}
thisRow.add(val);
}
}
return thisRow;
}
}