Min Sum Path in Triangle
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.
Solution:
Time/Space: O(n^2)
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> a) {
int m = a.size();
// dp[i][j] = minSum at i, j
// dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + A[i][j]
// dp[0][0] = A[0][0]
// min(dp[m - 1][j])
int[][] dp = new int[m][m];
dp[0][0] = a.get(0).get(0);
for (int i = 1; i < m; i ++) {
ArrayList<Integer> row = a.get(i);
int n = row.size();
dp[i][0] = dp[i - 1][0] + row.get(0);
dp[i][n - 1] = dp[i - 1][n - 2] + row.get(n - 1);
for (int j = 1; j < n - 1; j ++) {
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + row.get(j);
}
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < a.get(m - 1).size(); j ++) {
min = Math.min(min, dp[m - 1][j]);
}
return min;
}
}
Space optimized:
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> a) {
int m = a.size();
// dp[i][j] = minSum at i, j
// dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + A[i][j]
// dp[0][0] = A[0][0]
// min(dp[m - 1][j])
int[] dp = new int[m];
dp[0] = a.get(0).get(0);
for (int i = 1; i < m; i ++) {
ArrayList<Integer> row = a.get(i);
int[] temp = new int[m];
int n = row.size();
temp[0] = dp[0] + row.get(0);
temp[n - 1] = dp[n - 2] + row.get(n - 1);
for (int j = 1; j < n - 1; j ++) {
temp[j] = Math.min(dp[j - 1], dp[j]) + row.get(j);
}
dp = temp;
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < a.get(m - 1).size(); j ++) {
min = Math.min(min, dp[j]);
}
return min;
}
}