zoukankan      html  css  js  c++  java
  • [Leetcode] 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 is11(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.

     题意:寻找一条从顶端到底端和最小的路径

    思路:动态规划。【自己开始的思考过程:(可忽略)若是维护一个二维数组,很容易找到的是,针对某一个triangle元素,dp[i][j]=min(dp[i-1][j-1],dp[i-1][j])+triangle[i][j] ,即上面中较小的一个。从上到下的寻找,会发现有的元素的前一个或者后一个不存在】。从下往上寻找最小路径和。维护一个一维数组dp[ ] ,大小为n,到达上一层某个点的最小路径和是为到达下一层列相邻两个元素的时最小路径和中的较小一个加上当前值,即转移方程为;dp[j]=min(dp[j],dp[j+1])+triangle[i][j];在处理行数和列数之间的关系时,没有想到整个二维矩阵的行列不相等而是某一行所在的行数等于该行的列数,即是变化的,参考了Grandyang了才知道的,还有就是dp数字初始化的方式,也值得参考。至于为什么返回dp[0],可以多想想过程。这里给出代码:

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) 
     4     {
     5         int n=triangle.size();
     6         vector<int> dp(triangle.back());
     7         for(int i=n-2;i>=0;i--)
     8         {
     9             for(int j=0;j<=i;j++)
    10             {
    11                 dp[j]=min(dp[j],dp[j+1])+triangle[i][j];
    12             }
    13         }    
    14         return dp[0];
    15     }
    16 };

    另一种思路:也是从下往上加,只不过,这个最短路径的中间值是存在二维矩阵中,即改变了原本数组。

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) 
     4     {
     5         for (int i = triangle.size() - 2; i >= 0; --i)
     6             for (int j = 0; j < i + 1; ++j)
     7             {   //加上较小值
     8                 if(triangle[i+1][j] > triangle[i+1][j+1])
     9                 {
    10                     triangle[i][j] += triangle[i+1][j+1];
    11                 }
    12                 else
    13                 {
    14                     triangle[i][j] += triangle[i+1][j];
    15                 }
    16             }
    17         
    18         return triangle[0][0];
    19     }
    20 };
  • 相关阅读:
    spider-抓取页面内容
    Zabbix监控
    时间戳转换
    计算机脱域
    查询指定时间内审核失败的事件日志
    spider-抓取网页内容(Beautiful soup)
    Queue
    spider-抓取网页内容
    MyEclipse+Tomcat配置
    Gradle Java Web应用程序并在Tomcat上运行
  • 原文地址:https://www.cnblogs.com/love-yh/p/7117091.html
Copyright © 2011-2022 走看看