动态规划—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 is11(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.

思路:

题目的意思是找出从顶到底的最小路径和,类似二叉树。

从下向上进行,例如第i+1行的第j和j+1元素进行比较,将两元素中较小的值与第i行的第j个元素相加,以此类推,最后顶元素就是要求的最小路径和。

代码:

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