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.
=================
Analysis:
It is a tougth question (for me), we do not have the "bottom-up" idea.
If we start calculate the path sums from top of the triangle to the bottom, we have to tranverse all the possible paths (O(2^n)). Because, if we only choose the smaller adjacent number in the next level, we cannot ensure the sum of the WHOLE path is smaller than the other one.
However, if we start calculate the path sums from the bottom of the triangle to the top, we can always choose the current smaller path. This is because, in this approach, we are not comparing to number in the previous level, but the sums of these two paths till previous level. (O(n^2))
After having this "bottom-up" idea, the implementation is strait forward. We need an array to keep the path sums, but only the path with smallest sum will reach the top level.
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
int[] path = new int[triangle.size()];
// init the path sum as the values at the bottom of the triangle
for(int i=0; i<triangle.size(); i++) path[i]=triangle.get(triangle.size()-1).get(i);
// calculate the path level by level upward
for(int i=triangle.size()-2; i>=0; i--){
for(int j=0; j<=i; j++){// for each element in current level
// sum of current path = current value + the smaller adjacent numbers from previous level
path[j] = triangle.get(i).get(j) + Math.min(path[j], path[j+1]);
}
}
return path[0];
}
}