[Leetcode] Triangle 三角形

519 查看

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).

动态规划

复杂度

时间 O(NM) 空间 O(1)

思路

这题我们可以从上往下依次计算每个节点的最短路径,也可以自下而上。自下而上要简单一些,因为我们只用在两个下方元素中选一个较小的,就能得到确定解。如果将上一层的累加和存在一个一维数组里,则可以只用O(n)空间,但实际上我们可以直接in place在输入list中修改值,就可以不用额外空间了。

代码

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        for(int i = triangle.size() - 2; i >= 0; i--){
            for(int j = 0; j < triangle.get(i).size(); j++){
                triangle.get(i).set(j,triangle.get(i).get(j)+Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)));
            }
        }
        return triangle.get(0).get(0);
    }
}