zoukankan      html  css  js  c++  java
  • Triangle

    Description:

    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.

    Code:

     1   int minimumTotal(vector<vector<int> > &triangle) {
     2         //注意三角形的存储顺序,顶端是第一行数据
     3         if (triangle.empty())
     4             return 0;
     5         int row = triangle.size();
     6         
     7         vector<int>nextRow(triangle[row-1]);
     8         vector<int>currentRow;
     9         for (int i = row-2; i >= 0; --i)
    10         {
    11             int col = triangle[i].size();
    12             currentRow = triangle[i];
    13             for (int j = 0; j < col; ++j)
    14             {
    15                 currentRow[j] += min(nextRow[j], nextRow[j+1]);
    16             }
    17             nextRow = currentRow;
    18         }
    19         return nextRow[0];
    20     }
  • 相关阅读:
    Django后台admin的使用
    $(.ajax)的使用
    centos7配置双网卡bond
    vsftpd服务的搭建
    linu重置root密码(CentOS7)
    python内置函数
    元组和字典的魔法
    列表的魔法
    字符串的魔法
    zabbix-get
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4590698.html
Copyright © 2011-2022 走看看