Skip to content

Commit a0de094

Browse files
refactor 120
1 parent 59bdb74 commit a0de094

File tree

1 file changed

+13
-30
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+13
-30
lines changed

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

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,21 @@
22

33
import java.util.List;
44

5-
/**
6-
* 120. Triangle
7-
8-
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
9-
10-
For example, given the following triangle
11-
[
12-
[2],
13-
[3,4],
14-
[6,5,7],
15-
[4,1,8,3]
16-
]
17-
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
18-
19-
Note:
20-
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.*/
21-
225
public class _120 {
23-
public static class Solution1 {
24-
public int minimumTotal(List<List<Integer>> triangle) {
25-
int n = triangle.size();
26-
List<Integer> cache = triangle.get(n - 1);
6+
public static class Solution1 {
7+
public int minimumTotal(List<List<Integer>> triangle) {
8+
int n = triangle.size();
9+
List<Integer> cache = triangle.get(n - 1);
2710

28-
for (int layer = n - 2; layer >= 0; layer--) {
29-
//for each layer
30-
for (int i = 0; i <= layer; i++) {
31-
//check its very node
32-
int value = Math.min(cache.get(i), cache.get(i + 1)) + triangle.get(layer).get(i);
33-
cache.set(i, value);
11+
for (int layer = n - 2; layer >= 0; layer--) {
12+
//for each layer
13+
for (int i = 0; i <= layer; i++) {
14+
//check its very node
15+
int value = Math.min(cache.get(i), cache.get(i + 1)) + triangle.get(layer).get(i);
16+
cache.set(i, value);
17+
}
18+
}
19+
return cache.get(0);
3420
}
35-
}
36-
return cache.get(0);
3721
}
38-
}
3922
}

0 commit comments

Comments
 (0)