Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Notice
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.
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).
这道题花了一阵功夫才把++改成--, 感觉自己很危险啊。
代码:
public int minimumTotal(int[][] triangle) {
// write your code here
if(triangle == null || triangle.length == 0 || triangle[0].length == 0) return 0;
if(triangle.length == 1) return triangle[0][0];
for(int i= triangle.length-2;i>=0;i--){
for(int j=0;j<triangle[i].length;j++){
//System.out.println(j);
triangle[i][j] += Math.min(triangle[i+1][j], triangle[i+1][j+1]);
}
}
return triangle[0][0];
}