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     }
  • 相关阅读:
    SPOJ distinct subtrings
    OI题目类型总结整理
    emacs 考场配置
    SDOI2013 费用流
    HAOI2011 problem a
    BZOJ3438 小M的作物(和拓展)
    APIO2014 连珠线
    NOI2009 管道取珠
    HNOI2013 切糕
    NOI2009 植物大战僵尸
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4590698.html
Copyright © 2011-2022 走看看