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.
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int m = triangle.size();
if(m == 0)return 0;
//int n = triangle[0].length;
for(int i=1;i<m;i++){
int n = triangle.get(i).size();
//先更新两头
triangle.get(i).set(0,triangle.get(i-1).get(0)+triangle.get(i).get(0));
triangle.get(i).set(n-1,triangle.get(i-1).get(n-2)+triangle.get(i).get(n-1));
for(int j=1;j<n-1;j++){
int min = Math.min(triangle.get(i-1).get(j-1),triangle.get(i-1).get(j));//找比较小的那个
triangle.get(i).set(j,triangle.get(i).get(j)+min);
}
}
int res = Integer.MAX_VALUE;
for(int i=0;i<triangle.get(m-1).size();i++){
if(res>triangle.get(m-1).get(i)){
res = triangle.get(m-1).get(i);
}
}
return res;
}
}