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.
这个题其实挺有意思的,主要后面说,要只用O(n)的空间来做这个题。
这个题一开始没做出来,我发现我永远是naive的思路。。。:找最小值,嗯,每次只能往下方相邻的数字走,那就遍历吧,每个只能向下或者向右下走,选它们的最小值,那么设个当前的current,一开始current=0,当current到了最底的时候返回。 但这样会发现,太耗时。
路径会走重复。比如说2->3->5->1和2->4->5->1, 5->1就是重复的计算,当数组比较少的时候看不出来,当很大的时候,就会有很多重复的运算。所以这种方式不可取。
其实后来发现,用dp简直就是完美。做过leetcode的其他题的同学会发现,很多dp题都是这样的思路。比如说那个climbing stairs, unique path。 其实都有个前提条件,要么走一个方向,要么走另一个方向。爬梯子是,要么走一步,要么走两步。 唯一路径那个题是,要么向下走,要么想右走
这样总结起来其实思路就清晰了,这个题中,不管你怎么走, 第(x,y)点的值,肯定是它上面(x,y-1)和左上(x-1,y-1)的点,加上现在这个点的值得来了的。按这个题的例子:“1”那个点,只能是从5,或者6,累加过来的,具体值是多少,我们不知道,但是只有这两种可能性。按照题意,我们想要最小的值,那么我们的dp方程就可以写出dp(x,y)=min(dp(x,y-1),dp(x-1,y-1))+valueOfThisPoint
但要注意的是,最右边的点,没有上面的点,最左面的点,没有左上的点。这两种情况,值是唯一的。
第二个注意点是,只要o(n)空间,其实这一层的累加和,只和上一层有关。所以我们只要开辟一个n的空间,从上往下,逐层刷新值,最后一行,肯定有一个是最小的值,这就是结果。具体过程在纸上按照dp的方程列一个表画画就会很清晰了。代码如下:
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
int len=triangle.size();
int[] dpInfo=new int[len];
dpInfo[0]=triangle.get(0).get(0);
if(len<=1) return dpInfo[0];
for(int i=1;i<=len-1;i++){
int a=i;
while(a>=0){
int thislevel=triangle.get(i).get(a);
if(a==i) dpInfo[a]=dpInfo[a-1]+thislevel;
else if(a==0) dpInfo[a]=dpInfo[a]+thislevel;
else dpInfo[a]=Math.min(dpInfo[a],dpInfo[a-1])+thislevel;
a--;
}
}
int result=dpInfo[0];
for(int i=1;i<len;i++){
result=Math.min(result,dpInfo[i]);
}
return result;
}