题目:
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.
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int min=minSum(triangle,1,0);
return min;
}
private int minSum(List<List<Integer>> triangle,int l, int i){
if(l==triangle.size()){
List<Integer> t = triangle.get(l-1);
return t.get(i);
}
List<Integer> t = triangle.get(l-1);
int left=t.get(i)+minSum(triangle,l+1,i);
int right=t.get(i)+minSum(triangle,l+1,i+1);
return left>right? right:left;
}
}
解决方法二: 广度优先搜索思想
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(null==triangle||triangle.size()<=0)return 0;
LinkedList<Integer> sum = new LinkedList<Integer>();
sum.add(triangle.get(0).get(0));
int min=0;
for(int i=1;i<triangle.size();i++){
List<Integer> t = triangle.get(i);
for(int j=0;j<=i;j++){
if(j==0) min=sum.peekFirst()+t.get(j);
else if(j==i) min=sum.pollFirst()+t.get(j);
else{
min=Math.min(sum.pollFirst(),sum.peekFirst())+t.get(j);
}
sum.addLast(min);
}
}
min=Integer.MAX_VALUE;
for(Integer i:sum){
min=min<i?min:i;
}
return min;
}
}
解决方法三: 动态规划 Runtime: 11 ms
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(null==triangle||triangle.size()<=0)return 0;
ArrayList<Integer> min = new ArrayList<Integer>();
List<Integer> t = triangle.get(triangle.size()-1);
for(int i=0;i<t.size();i++)
min.add(t.get(i));
for(int i=triangle.size()-2;i>=0;i--){
t=triangle.get(i);
for(int j=0;j<t.size();j++){
min.set(j,Math.min(min.get(j),min.get(j+1))+t.get(j));
}
}
return min.get(0);
}
}
参考: