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.
解题思路为每个点找出最小的路径值:
2
/ \
5 6
/ \ / \
11 10 13
/ \ / \ / \
15 11 18 16
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for (int i = 1; i < triangle.size(); i++) {
for (int j = 0; j < triangle.get(i).size(); j++) {
List<Integer> now = triangle.get(i);
List<Integer> before = triangle.get(i-1);
if(j == 0 ) {
now.set(j, now.get(j)+before.get(0));
}else if(j == triangle.get(i).size()-1){
now.set(j, now.get(j)+before.get(before.size()-1));
}else {
now.set(j, Math.min(before.get(j), before.get(j-1))+now.get(j));
}
}
}
int value = triangle.get(triangle.size()-1).get(0);
for(int i=1;i<triangle.get(triangle.size()-1).size();i++) {
value = Math.min(value, triangle.get(triangle.size()-1).get(i));
}
return value;
}
}