-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriangle_120.java
More file actions
79 lines (73 loc) · 2.44 KB
/
Copy pathTriangle_120.java
File metadata and controls
79 lines (73 loc) · 2.44 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.leetcode.dynamicprogram;
import java.util.AbstractCollection;
import java.util.List;
/**
* Created by charles on 1/31/17.
* 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).
*/
public class Triangle_120 {
/**
* Bottom-Up DP, start from bottom row,
* State : dp[i][j] is min pathsum at jth node on ith row
* function: dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j];
* init: bottom
* answer : dp[0][0]
*/
public int minimumTotalSpaceOptimize(List<List<Integer>> triangle) {
int n = triangle.size();
int[] dp = new int[n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
}
}
return dp[0];
}
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[][] dp = new int[n + 1][n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
dp[i][j] = Math.min(dp[i + 1][j], dp[i+1][j+1]) + triangle.get(i).get(j);
}
}
return dp[0][0];
}
public int minimunTotalTopDown(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return -1;
}
if (triangle.get(0) == null || triangle.get(0).size() == 0) {
return -1;
}
// state : dp[i][j] = minimum path value from 0,0 to i,j
int n = triangle.size();
int[][] dp = new int[n][n];
// init
dp[0][0] = triangle.get(0).get(0);
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + triangle.get(i).get(0);
dp[i][i] = dp[i - 1][i - 1] + triangle.get(i).get(i);
}
// top down
for (int i = 1; i < n; i++) {
for (int j = 1; j < i; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle.get(i).get(j);
}
}
// answer --> iterate all res at last row
int min = dp[n - 1][0];
for (int i = 1; i < n; i++) {
min = Math.min(min, dp[n - 1][i]);
}
return min;
}
}