LeetCode Triangle(dp)

来源:互联网 发布:ubuntu kernel 编辑:程序博客网 时间:2024/06/07 22:58


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(x,y)表示从(0,0)到(x,y)的最短路径,f(x,y)表示元素值,则状态转移方程为

        dp(x,y)=min{dp(x-1,y), dp(x, y -1)} + f(x,y)

代码如下:

public class Solution {    public int minimumTotal(List<List<Integer>> triangle)     {        List<List<Integer>> res = new ArrayList<List<Integer>>();        List<Integer> tmp = new ArrayList<Integer>();        if (triangle.size() > 0) {            tmp.add(triangle.get(0).get(0));            res.add(tmp);        }                for (int i = 0; i < triangle.size() - 1; i++) {            tmp = new ArrayList<Integer>();            for (int j = 0; j < triangle.get(i).size(); j++) {                int t1 = res.get(i).get(j) + triangle.get(i + 1).get(j);                int t2 = res.get(i).get(j) + triangle.get(i + 1).get(j + 1);                if (j >= tmp.size()) tmp.add(t1);                else {                    int t = Math.min(t1, tmp.get(j));                    tmp.set(j, t);                }                                if (j + 1 >= tmp.size()) tmp.add(t2);                else {                    int t = Math.min(t2, tmp.get(j + 1));                    tmp.set(j + 1, t);                }            }            res.add(tmp);        }                int n = res.size();        int ans = Integer.MAX_VALUE;        for (int i = 0; i < res.get(n - 1).size(); i++) {            ans = Math.min(ans, res.get(n - 1).get(i));        }                return ans;    }}

0 0
原创粉丝点击