forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_118.java
69 lines (64 loc) · 2.24 KB
/
_118.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _118 {
public static class Solution1 {
/**
* fill out values from left to right
*/
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
List<Integer> row = new ArrayList();
for (int i = 0; i < numRows; i++) {
row.add(0, 1);
for (int j = 1; j < row.size() - 1; j++) {
row.set(j, row.get(j) + row.get(j + 1));
}
result.add(new ArrayList(row));
}
return result;
}
}
public static class Solution2 {
/**
* fill out values from right to left
* credit: https://leetcode.com/problems/pascals-triangle/discuss/38141/My-concise-solution-in-Java/36127
*/
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
List<Integer> row = new ArrayList();
for (int i = 0; i < numRows; i++) {
for (int j = row.size() - 1; j >= 1; j--) {
row.set(j, row.get(j) + row.get(j - 1));
}
row.add(1);
result.add(new ArrayList<>(row));
}
return result;
}
}
public static class Solution3 {
/**
* my completely original solution on 9/15/2021
*/
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
if (ans.isEmpty()) {
ans.add(Arrays.asList(1));
} else {
List<Integer> prev = ans.get(ans.size() - 1);
List<Integer> curr = new ArrayList<>(prev.size() + 1);
curr.add(1);
for (int j = 0; j < prev.size() - 1; j++) {
curr.add(prev.get(j) + prev.get(j + 1));
}
curr.add(1);
ans.add(curr);
}
}
return ans;
}
}
}