120. Triangle java solutions

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 }
 如果题中没有负数的,其实可以用贪心做的。(注意:下面代码是无法AC的)
 1 public class Solution {
 2     public int minimumTotal(List<List<Integer>> triangle) {
 3         int len = triangle.size();
 4         int ans = triangle.get(0).get(0);
 5         int index = 0;
 6         for(int i = 1; i <len; i++){
 7             ans += Math.min(triangle.get(i).get(index),triangle.get(i).get(index+1));
 8             index = triangle.get(i).get(index) < triangle.get(i).get(index+1) ? index : index + 1;
 9         }
10         return ans;
11     }
12 }

 

posted @ 2016-07-03 15:31  Miller1991  阅读(201)  评论(0编辑  收藏  举报