题目:Triangle
难度:medium
问题描述:
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.
解题思路:一开始使用DFS的方法,很简单但是超时了。。。后来想到使用动态规划,从第一层开始,修改每个I层每个j数的值,使得该数变为从0层到该数的最小和。
比如Table[1][0]+=table[0][0],table[2][1]+=MIN(tale[1][0],table[1][1])...
不过此题给的是list,直接取数效率很低下(比如我的方法),使用迭代器可能会快很多。
代码如下:
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int level=triangle.size();
if(level==1){
return triangle.get(0).get(0);
}
for(int i=1;i<level;i++){
for(int j=0;j<=i;j++){
//第i层 第j个 i>1
if(j>0){
if(j<i){
triangle.get(i).set(j,triangle.get(i).get(j)+Math.min(triangle.get(i-1).get(j-1), triangle.get(i-1).get(j)));
}else{
//j==i
triangle.get(i).set(j, triangle.get(i-1).get(j-1)+triangle.get(i).get(j));
}
}else{
//j==0
triangle.get(i).set(0, triangle.get(i-1).get(0)+triangle.get(i).get(0));
}
}
}
int temp=Integer.MAX_VALUE;
for(int w:triangle.get(level-1)){
temp=temp>w?w:temp;
}
return temp;
}
}