Leetcode 120. Triangle 三角形问题(动态规划经典) 解题报告

来源:互联网 发布:淘宝怎么搜索关键词 编辑:程序博客网 时间:2024/05/16 12:41

1 解题报告

首先我承认我很二哈,这道题我明明已经做过了,但是刚刚不知道为什么又去做了一遍,而且我查了下两次的解法还有所差别(貌似是现在的版本有进步了呢)

问题就是一个三角形的数组,求从顶部到下方的最短路径。。

这个问题是太过经典+Easy的DP问题了,哈哈。。

不想多讲,直接看吧

PS:其实这道题倒着从底部到顶部也可以

2 原题

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. Subscribe to see which companies asked this question

3 今天做的版本

今天做的版本我着重写了下注释,而且用的方法更加省内存了~~

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        /*         典型的动态规划问题         对于层数i的第j个节点有:dp[i][j] = triangle[i][j] + min(dp[i-1][j-1],dp[i-1][j]) (注意特殊处理边界)         改善:只使用O(n)的弓箭,那么就只弄一层,使用一个lastVal来代替dp[i-1][j-1]        */        int n = triangle.size();        int dp[] = new int[n];        //第一个为0 其他为max        for(int i=1;i<n;i++) dp[i] = Integer.MAX_VALUE;        int lastVal,tmp;        for(int i=0;i<n;i++){           lastVal = Integer.MAX_VALUE;           for(int j=0;j<=i;j++){               tmp = dp[j];               dp[j] = triangle.get(i).get(j) + Math.min(dp[j],lastVal);               lastVal = tmp;           }         }        int res = Integer.MAX_VALUE;        for(int i=0;i<n;i++)             res = Math.min(res,dp[i]);        return res;    }}

4 很久前做的版本

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        if(triangle.size()==0)            return 0;        int dp[]=new int[triangle.size()];        int last[]=new int[triangle.size()];        int tmp[];        dp[0]=triangle.get(0).get(0);        last[0]=triangle.get(0).get(0);        for(int i=1;i<triangle.size();i++){            List<Integer> line=triangle.get(i);            dp[0]=line.get(0)+last[0];            dp[i]=line.get(i)+last[i-1];            for(int j=1;j<i;j++){                dp[j]=Math.min(last[j],last[j-1])+line.get(j);            }            tmp=last;            last=dp;            dp=tmp;        }        int result=last[0];        for(int i=1;i<triangle.size();i++){            result=Math.min(result,last[i]);        }        return result;    }}
0 0
原创粉丝点击