• *Triangle


    题目

    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.

    题解:

    一道动态规划的经典题目。需要自底向上求解。

    递推公式是: dp[i][j] = dp[i+1][j] + dp[i+1][j+1] ,当前这个点的最小值,由他下面那一行临近的2个点的最小值与当前点的值相加得到。

    由于是三角形,且历史数据只在计算最小值时应用一次,所以无需建立二维数组,每次更新1维数组值,最后那个值里存的就是最终结果。

    代码如下:

     1 public int minimumTotal(List<List<Integer>> triangle) {
     2     if(triangle.size()==1)
     3         return triangle.get(0).get(0);
     4         
     5     int[] dp = new int[triangle.size()];
     6 
     7     //initial by last row 
     8     for (int i = 0; i < triangle.get(triangle.size() - 1).size(); i++) {
     9         dp[i] = triangle.get(triangle.size() - 1).get(i);
    10     }
    11  
    12     // iterate from last second row
    13     for (int i = triangle.size() - 2; i >= 0; i--) {
    14         for (int j = 0; j < triangle.get(i).size(); j++) {
    15             dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
    16         }
    17     }
    18  
    19     return dp[0];
    20 }

    Reference:  http://www.programcreek.com/2013/01/leetcode-triangle-java/

     
  • 相关阅读:
    Guns项目整体结构
    基于事件的NIO多线程服务器
    Reactor模式和NIO
    ConcurrentHashMap之实现细节
    C 语言的前世今生
    Netty系列之Netty高性能之道
    java synchronized详解
    生产者/消费者模式
    当spring 容器初始化完成后执行某个方法
    Linux系统管理员需要知道的16个服务器监控命令
  • 原文地址:https://www.cnblogs.com/hygeia/p/4618881.html
Copyright © 2020-2023  润新知