# Leetcode120 三角矩阵，从顶到低端的最短路径

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 ret=0;
int n =triangle.size();
for(int i=1;i<n;i++ ){
List<Integer> dataList = triangle.get(i);

int len = dataList.size();
for(int j=0;j<len;j++){
if(j-1>=0 && j!=len -1){
if(triangle.get(i-1).get(j-1)< triangle.get(i-1).get(j)){
dataList.set(j, triangle.get(i-1).get(j-1)+dataList.get(j));
continue;
}
}
if(j==len -1){
dataList.set(j, triangle.get(i-1).get(j-1)+dataList.get(j));
break;

}
dataList.set(j, triangle.get(i-1).get(j)+dataList.get(j));

}
triangle.set(i, dataList);

}
ret = triangle.get(n-1).get(0);
for(int i=1;i<n;i++){
if(ret>triangle.get(n-1).get(i)){
ret=triangle.get(n-1).get(i);
}

}

return ret;
}
}

class Solution {
public int minimumTotal(List<List<Integer>> triangle) {

int n =triangle.size();
int[] tempList=new int[n];
for(int k=0;k<n;k++){
tempList[k]=triangle.get(n-1).get(k).intValue();
}

for(int i = n-2;i>=0;i--){
int len = triangle.get(i).size();
for(int j=0;j<len;j++){
tempList[j]=triangle.get(i).get(j)+ Math.min(tempList[j], tempList[j+1]);

}

}

return tempList[0];
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120