Skip to content

Commit 23e0ca9

Browse files
add a solution for 118
1 parent ad8c02c commit 23e0ca9

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/main/java/com/fishercoder/solutions/_118.java

+25
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.fishercoder.solutions;
22

33
import java.util.ArrayList;
4+
import java.util.Arrays;
45
import java.util.List;
56

67
public class _118 {
@@ -41,4 +42,28 @@ public List<List<Integer>> generate(int numRows) {
4142
return result;
4243
}
4344
}
45+
46+
public static class Solution3 {
47+
/**
48+
* my completely original solution on 9/15/2021
49+
*/
50+
public List<List<Integer>> generate(int numRows) {
51+
List<List<Integer>> ans = new ArrayList<>();
52+
for (int i = 0; i < numRows; i++) {
53+
if (ans.isEmpty()) {
54+
ans.add(Arrays.asList(1));
55+
} else {
56+
List<Integer> prev = ans.get(ans.size() - 1);
57+
List<Integer> curr = new ArrayList<>(prev.size() + 1);
58+
curr.add(1);
59+
for (int j = 0; j < prev.size() - 1; j++) {
60+
curr.add(prev.get(j) + prev.get(j + 1));
61+
}
62+
curr.add(1);
63+
ans.add(curr);
64+
}
65+
}
66+
return ans;
67+
}
68+
}
4469
}

src/test/java/com/fishercoder/_118Test.java

+7
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
public class _118Test {
99
private static _118.Solution1 solution1;
1010
private static _118.Solution2 solution2;
11+
private static _118.Solution3 solution3;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _118.Solution1();
1516
solution2 = new _118.Solution2();
17+
solution3 = new _118.Solution3();
1618
}
1719

1820
@Test
@@ -25,4 +27,9 @@ public void test2() {
2527
CommonUtils.printListList(solution2.generate(5));
2628
}
2729

30+
@Test
31+
public void test3() {
32+
CommonUtils.printListList(solution3.generate(5));
33+
}
34+
2835
}

0 commit comments

Comments
 (0)