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 is11
(i.e.,2+3+5+1= 11).
Note:
Bonus point if you are able to do this using onlyO(n) extra space, wherenis the total number of rows in the triangle.
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) return 0;
int n = triangle.size();
int[][] dp = new int[n][n];
dp[0][0] = triangle.get(0).get(0);
for (int i = 1; i < n; i++){
for (int j = 0; j < triangle.get(i).size(); j++){
Integer prev1 = null;
Integer prev2 = null;
if (j - 1 >= 0 && j - 1 < triangle.get(i - 1).size()) prev1 = dp[i - 1][j - 1];
if (j >= 0 && j < triangle.get(i - 1).size()) prev2 = dp[i - 1][j];
int prev = Integer.MAX_VALUE;
if (prev1 != null) prev = Math.min(prev, prev1);
if (prev2 != null) prev = Math.min(prev, prev2);
dp[i][j] = triangle.get(i).get(j) + prev;
//System.out.println("i: " + i + " j: " + j + " dp: " + dp[i][j]);
}
}
int ans = Integer.MAX_VALUE;
for (int j = 0; j < triangle.get(n - 1).size(); j++){
ans = Math.min(ans, dp[n - 1][j]);
}
return ans;
}
}