Triangle

来源:互联网 发布:ubuntu安装vim8离线包 编辑:程序博客网 时间:2024/05/16 16:00

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, wheren is the total number of rows in the triangle.

思路: 首先发现层与层之间有依赖关系,需要记录之前的历史信息,很自然想到用dp来做。
从下往上计算,容易写,而且省空间,不用二维数组,用一维数组就可以记录。dp[i]表示的物理意义是:这个坐标点,在当前层最短路径算出来的最小值。
然后最后return dp[0]就是所求。递推公式很容易得出来:
i是层数,j是每层的index: 
dp[j] = Math.min(dp[j], dp[j+1]) + triangle.get(i).get(j);
public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        if(triangle == null || triangle.size() == 0) return 0;        int[] dp = new int[triangle.get(triangle.size()-1).size()];        for(int i=0; i<dp.length; i++){            dp[i] = triangle.get(triangle.size()-1).get(i);        }                for(int i=triangle.size()-2; i>=0; i--){            for(int j=0; j<triangle.get(i).size(); j++){                dp[j] = Math.min(dp[j], dp[j+1]) + triangle.get(i).get(j);            }        }        return dp[0];    }}





0 0
原创粉丝点击