题目描述:
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).
中文理解:
给定一个二维不定长的数列,求从最上层到底层的最短距离。
解题思路:
动态规划,首先初始化第一行为原数列的第一行,第一列的值为上面行的第一列的值累加,然后根据递推公式求得每个位置的值dp[i][j]=Math.min(dp[i-1][j],dp[i-1][j-1])+triangle[i][j]。不过由于是不定长的数列,所以需要提前判断上一行的正上方和左上方是否有值。
代码(java):
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
ArrayList<ArrayList<Integer>> dp=new ArrayList();
ArrayList<Integer> temp=new ArrayList();
for(int i=0;i<triangle.size();i++){
temp=new ArrayList();
if(i==0){
//将dp的第一行的值设为triangle的值
for(int j=0;j<triangle.get(i).size();j++){
temp.add(triangle.get(i).get(j));
}
}
else{
for(int j=0;j<triangle.get(i).size();j++){
if(j==0){
//将第一列的值设置为以上所有行第一列元素之和
temp.add(triangle.get(i).get(j)+dp.get(i-1).get(j));
}
else temp.add(0);
}
}
dp.add(new ArrayList(temp));
}
//动态规划
for(int i=1;i<triangle.size();i++){
for(int j=1;j<triangle.get(i).size();j++){
int aboveleft=Integer.MAX_VALUE,aboveon=Integer.MAX_VALUE;
if(dp.get(i-1).size()-1>=j-1)aboveleft=dp.get(i-1).get(j-1);
if(dp.get(i-1).size()-1>=j)aboveon=dp.get(i-1).get(j);
temp=dp.get(i);
temp.set(j,Math.min(aboveleft,aboveon)+triangle.get(i).get(j));
}
}
int min=Integer.MAX_VALUE;
for(int val:dp.get(dp.size()-1)){
min=Math.min(val,min);
}
return min;
}
}