-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathArray-120-Triangle
33 lines (28 loc) · 1.01 KB
/
Array-120-Triangle
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
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
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.
==================================
class Solution {
public int minimumTotal(List<List<Integer>> tri) {
int row = tri.size();
int[] count = new int[row];
List<Integer> lastRow = tri.get(row - 1);
for(int j = 0; j < row; j++)
count[j] = lastRow.get(j);
for(int i = row - 2; i > -1; i--){
List<Integer> thisRow = tri.get(i);
for(int j = 1; j < thisRow.size() + 1; j++){
count[j - 1] = Math.min(count[j - 1], count[j]) + thisRow.get(j - 1);
}
}
return count[0];
}
}