120. Triangle

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.

本题使用DP方法来解决,DP方法的描述是原问题可以分解成规模较小的子问题,不过子问题与原问题是一样的,只不过规模变小了,也就是说,原问题是三角形,求sum最小值,那么子问题也应该是三角形,求最小值。那么我们可以推测,做题顺序肯定是从三角形的底边开始逐渐往上递归。因为如果从上往下计算的话,那么子问题将不是三角形。DP有两个特点,最优子结构和重叠子问题。其中最优子结构这一步并不一定是上一步的最优解+cur值,这是和greedy最大的区别。重叠子问题很明显,用cur的链表保存了它下面的所有数的的sum最小和。本题的最优解是隐含的,最小值是蕴含在链表里面的,而不像其他的题目,最优解是max或者min。代码如下:

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         for(int i=triangle.size()-2;i>=0;i--){
 4             for(int j=0;j<triangle.get(i).size();j++){
 5                 triangle.get(i).set(j,Math.min(triangle.get(i+1).get(j),triangle.get(i+1).get(j+1))+triangle.get(i).get(j));
 6             }
 7         }
 8         return triangle.get(0).get(0);
 9     }
10 }
原文地址:https://www.cnblogs.com/codeskiller/p/6384908.html