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

    1 [
    2      [2],
    3     [3,4],
    4    [6,5,7],
    5   [4,1,8,3]
    6 ]

      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 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) {
     4         int rows = triangle.size();
     5         if(rows == 0)
     6             return 0;
     7         
     8         int * dp = new int[rows];
     9         int szOfLastRow = triangle[rows - 1].size();
    10         for(int i = 0; i < szOfLastRow; i++)
    11             dp[i] = triangle[rows - 1][i];
    12         
    13         for(int i = rows - 2; i > -1; i--)
    14         {
    15             int cols = triangle[i].size();
    16             for(int j = 0; j < cols; j++)
    17                 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
    18         }
    19         
    20         return dp[0];
    21     }
    22 };
    View Code

      这个程序中最核心的地方在:

    dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);

      可以用图表示如下:

      

      其中一个例子就是:

      

      需要注意的就是这个例子中只改变的是dp[0],dp[1]并没有改变。

  • 相关阅读:
    etcd的原理分析
    (转)Linux sort命令
    随机森林
    python 类的定义和继承
    python random
    Spark源码阅读(1): Stage划分
    Mac 上安装MySQL
    Python 删除 数组
    在循环中将多列数组组合成大数组
    准确率 召回率
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4562901.html
Copyright © 2011-2022 走看看