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.
clarification: Here "adjacent" of a[i][j] means a[i+1][j] and a[i][j+1], if available(not out of bound), while a[i+1][j-1] is not "adjacent" element.
Note: it's not necessary to worry about the boundary of the index. The length of row i+1 is always bigger than that of row i by 1, so here j+1 is always valid.
This is a typical DP problem and can be solved with both top-down recursive method and bottom-up DP table.
My Solutions:
Top-down recursive solution:
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if(triangle.size()==0) return -1;
int n = 0;
return minimumTotal(triangle, 0, n);
}
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle, int curLayer, int Index){
int ret =0;
int temp1=0, temp2=0;
if(curLayer == triangle.size()) return 0;
ArrayList<Integer> al = triangle.get(curLayer);
temp1 = minimumTotal(triangle, curLayer+1, Index);
temp2 = minimumTotal(triangle, curLayer+1, Index+1);
ret = temp1>=temp2? al.get(Index)+temp2 : al.get(Index)+temp1;
return ret;
}
This solution got TLE error in leetcode.
Bottom-up solution: (Note the O(n) extra space requirement, I used only an ArrayList<Integer> with the length equal to the last ArrayList from the input).漂亮!
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if(triangle.size()==0) return -1;
int n = triangle.size();
ArrayList<Integer> ret = new ArrayList<Integer>();
ArrayList<Integer> al = triangle.get(n-1);
for(int j= 0; j< al.size(); j++){
ret.add(al.get(j));
}
for(int i = n-2; i >= 0; i--){
al = triangle.get(i);
for(int j= 0; j< al.size(); j++){
int temp = ret.get(j)<=ret.get(j+1)?ret.get(j) :ret.get(j+1);
ret.set(j, al.get(j) + temp);
}
ret.remove(ret.size()-1);
}
return ret.get(0);
}
Pass the leetcode test!!
No comments:
Post a Comment