zoukankan      html  css  js  c++  java
  • 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.

     Notice

    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.

    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).

    Analyse: top to bottom dynamic programming.  

    Runtime: 22ms

     1 class Solution {
     2 public:
     3     /**
     4      * @param triangle: a list of lists of integers.
     5      * @return: An integer, minimum path sum.
     6      */
     7     int minimumTotal(vector<vector<int> > &triangle) {
     8         // write your code here
     9         if (triangle.empty() || triangle[0].empty()) return 0;
    10         int m = triangle.size();
    11         vector<int> dp(m, INT_MAX);
    12         
    13         dp[0] = triangle[0][0];
    14         for (int i = 1; i < m; i++) {
    15             for (int j = i; j > 0; j--) 
    16                 dp[j] = min(dp[j - 1], dp[j]) + triangle[i][j];
    17             dp[0] += triangle[i][0];
    18         }
    19         
    20         int result = INT_MAX;
    21         for (int i = 0; i < m; i++)
    22             result = min(result, dp[i]);
    23         return result;
    24     }
    25 };

    Analyse: Bottom to top dynamic programming.

    Runtime: 38ms

     1 class Solution {
     2 public:
     3     /**
     4      * @param triangle: a list of lists of integers.
     5      * @return: An integer, minimum path sum.
     6      */
     7     int minimumTotal(vector<vector<int> > &triangle) {
     8         // write your code here
     9         if (triangle.empty() || triangle[0].empty()) return 0;
    10         int m = triangle.size();
    11         vector<int> dp = triangle.back();
    12         
    13         for (int i = m - 2; i >= 0; i--) {
    14             for (int j = 0; j <= i; j++) {
    15                 dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j];
    16             }
    17         }
    18         return dp[0];
    19     }
    20 };
  • 相关阅读:
    在.NET访问MySql数据库时的几点经验(转)
    FxCop代码标准检测工具
    ASP(从前) vs ASP.NET(之后)
    NET本质论_读书笔记(1)
    WinDbg配置和使用基础(转)
    ASP.NET 2.0中CSS失效的问题总结(转)
    【下载】.NET Framework 源代码
    IL代码底层运行机制(转)
    asp.net水晶报表的一些问题
    Javascript 刷新框架及页面的方法总集
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5838540.html
Copyright © 2011-2022 走看看