Skip to content

Commit 1f95eb1

Browse files
committed
add solution of problem 120: triangle
1 parent 79dd7f4 commit 1f95eb1

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Triangle120/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
2+
3+
For example, given the following triangle
4+
```
5+
[
6+
[2],
7+
[3,4],
8+
[6,5,7],
9+
[4,1,8,3]
10+
]
11+
```
12+
The minimum path sum from top to bottom is `11` (i.e., 2 + 3 + 5 + 1 = 11).
13+
14+
####Note:
15+
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.

Triangle120/Solution.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class Solution {
2+
public int minimumTotal(List<List<Integer>> triangle) {
3+
if (triangle == null || triangle.size() == 0)
4+
return 0;
5+
6+
int size = triangle.size();
7+
int[] sum = new int[size];
8+
9+
List<Integer> lastList = triangle.get(size - 1);
10+
11+
int idx = 0;
12+
for (int val : lastList) {
13+
sum[idx++] = val;
14+
}
15+
16+
for (int i = size - 2; i >= 0; i--) {
17+
List<Integer> ls = triangle.get(i);
18+
int lsSize = ls.size();
19+
for (int j = 0; j < lsSize; j++) {
20+
int minValue = sum[j] < sum[j+1] ? sum[j] : sum[j+1];
21+
sum[j] = ls.get(j) + minValue;
22+
}
23+
}
24+
25+
return sum[0];
26+
}
27+
}

0 commit comments

Comments
 (0)