File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed
Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 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.
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments