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

120. Triangle java solutions

时间:2016-07-03 17:22:30      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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.

一开始是按照自顶向下的方式来寻找最小值,边界处理有点麻烦,调了几次。

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         int len = triangle.size();
 4         int[] dp = new int[len+1];
 5         Arrays.fill(dp,Integer.MAX_VALUE);
 6         dp[1] = triangle.get(0).get(0);
 7         
 8         for(int i = 1; i <len; i++){
 9             for(int j = triangle.get(i).size(); j > 0; j--){
10                 dp[j] = triangle.get(i).get(j-1) + Math.min(dp[j],dp[j-1]);
11             }
12         }
13         int min = Integer.MAX_VALUE;
14         for(int i = 1;i <= triangle.size(); i++){
15             min = Math.min(min,dp[i]);
16         }
17         return min;
18     }
19 }

 

 

解法二采用自底向上:

 

 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         int len = triangle.size();
 4         int[] dp = new int[len];
 5         for(int i = 0; i< len; i++){
 6             dp[i] = triangle.get(len-1).get(i);
 7         }
 8         for(int i = len-2; i>=0; i--){
 9             for(int j = 0; j < triangle.get(i).size(); j++){
10                 dp[j] = triangle.get(i).get(j) + Math.min(dp[j],dp[j+1]);
11             }
12         }
13         return dp[0];
14     }
15 }

 

120. Triangle java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5638103.html

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