File tree Expand file tree Collapse file tree 1 file changed +13
-30
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +13
-30
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import java .util .List ;
4
4
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
-
22
5
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 );
27
10
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 );
34
20
}
35
- }
36
- return cache .get (0 );
37
21
}
38
- }
39
22
}
You can’t perform that action at this time.
0 commit comments