[LeetCode]Triangle

来源:互联网 发布:非典生化武器知乎 编辑:程序博客网 时间:2024/06/08 02:08

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


本题难度Medium。

DP

【复杂度】
时间 O(MN) 空间 O(1)

【思路】
这道题目类似于长方形的格子从最左上到最右下的最短距离,都是用DP解决。如果我们把三角形倒过来进行计算就更方便:

 [  [4,1,8,3],   [6,5,7],    [3,4],     [2]]

比如第2行第1个6,该位置就是41的最小值与6之和。最后只要返回最后一行那个元素值即可(都不需要额外分配空间)。

【代码】

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        //invariant        for(int i=triangle.size()-2;i>=0;i--){            List<Integer> pre=triangle.get(i+1);            List<Integer> cur=triangle.get(i);            for(int j=0;j<cur.size();j++)                cur.set(j, cur.get(j)+Math.min(pre.get(j),pre.get(j+1)));        }        //ensure        return triangle.get(0).get(0);    }}
0 0
原创粉丝点击