码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java]Triangle@LeetCode

时间:2014-05-08 18:31:51      阅读:399      评论:0      收藏:0      [点我收藏+]

标签:style   class   code   java   ext   color   

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.

Runtime: 444 ms

 

动态规划思想: 从上到下一行一行的扫描并加入总体,dp[i]记录每扫描完一行,并途过本行i元素的最短路径,故dp[]记录到目前为止所有路径的长度。O(n) space

public class Solution {

    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {

        int[] dp=new int[triangle.size()];

        if(triangle.size()==0) return 0;

        if(triangle.size()==1) return triangle.get(0).get(0);

        dp[0]=triangle.get(0).get(0);

        for(int i=1;i<triangle.size();i++){

            for(int j=i;j>=0;j--){

                if(j==0) dp[0]+=triangle.get(i).get(0);

                else if(j<i) dp[j]=triangle.get(i).get(j)+ Math.min(dp[j],dp[j-1]);

                else dp[j]=dp[j-1]+triangle.get(i).get(j);

            }

        }

        int ret=Integer.MAX_VALUE;

        for(int i=0;i<dp.length;i++){

            if(dp[i]<ret) ret=dp[i];

        }

        return ret;

    }

}

[LeetCode][Java]Triangle@LeetCode,布布扣,bubuko.com

[LeetCode][Java]Triangle@LeetCode

标签:style   class   code   java   ext   color   

原文地址:http://www.cnblogs.com/oceanskkkkky/p/3715662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!