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.
解题:自己的思路是从上往下,类似于动态规划DP,遍历的时候替换元素为到达当前位置最短路径
public int minimumTotal(List<List<Integer>> triangle) {
int row = triangle.size();
for(int i=1;i<row;i++){
List<Integer> list = triangle.get(i);
for(int j=0;j<list.size();j++){
int up_min =0;
int temp =0;
if(j==0){
up_min = triangle.get(i-1).get(0);
temp = list.get(0)+up_min;
}else if(j==i){
up_min = triangle.get(i-1).get(j-1);
temp = list.get(j)+up_min;
}else{
int up_1 = triangle.get(i-1).get(j-1);
int up_2 = triangle.get(i-1).get(j);
temp = list.get(j)+((up_1<=up_2)?up_1:up_2);
}
list.set(j, temp);
}
}
//获取最后一行最小的数值
int result = triangle.get(row-1).get(0);
for(int i=0;i<triangle.size();i++){
if(triangle.get(row-1).get(i)<=result){
result = triangle.get(row-1).get(i);
}
}
return result;
}
改进:从下往上遍历
public int minimumTotal(List<List<Integer>> triangle) {
for(int i = triangle.size() - 2; i >= 0; i--)
for(int j = 0; j <= i; j++)
triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
return triangle.get(0).get(0);
}