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). 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,把到每一个点的最优路径算出来,利用上面算好的结果。最后选最后一层的最优解。
1,动态规划。到第i层的第k个顶点的最小路径长度表示为f(i,k),则f(i, k) = min{f(i-1,k), f(i-1,k-1)} + d(i, k); 其中d(i, k)表示原来三角形数组里的第i行第k列的元素。则可以求得从第一行到最终到第length-1行第k个元素的最小路径长度,最后再比较第length-1行中所有元素的路径长度大小,求得最小值。
2,本题主要关心的是空间复杂度不要超过n。
3,注意边界条件——每一行中的第一和最后一个元素在上一行中只有一个邻居。而其他中间的元素在上一行中都有两个相邻元素。
代码:
import java.util.*;public class Solution { public int minimumTotal(List
> triangle) { if (triangle == null || triangle.get(0) == null) return 0; int iLen = triangle.size(); for (int i=1; i