zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    ASP.NET MVC 学习: 视图
    翻译:ASP.NET MVC Example Application over Northwind with Entity Framework
    主流web2.0网站的配色参考方案
    jQuery1.2选择器
    ASP.NET MVC URL Routing 学习
    [转]关于DOM元素定位属性的深入学习
    ASP.NET MVC : Action过滤器(Filtering)
    【翻译】使用ASP.NET MVC 和LINQ建立一个简单的博客 Part 3
    Windows 8开发者训练营第一日来自现场的图片报道
    从数据到信息到决策
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5638103.html
Copyright © 2011-2022 走看看