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

    用从后往前更新的方法,就只需要O(n)的额外空间。

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> > &triangle) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (triangle.size() == 0)
     7             return 0;
     8             
     9         vector<int> f(triangle[triangle.size()-1].size());
    10         
    11         f[0] = triangle[0][0];
    12         for(int i = 1; i < triangle.size(); i++)
    13             for(int j = triangle[i].size() - 1; j >= 0; j--)
    14                 if (j == 0)
    15                     f[j] = f[j] + triangle[i][j];
    16                 else if (j == triangle[i].size() - 1)
    17                     f[j] = f[j-1] + triangle[i][j];
    18                 else
    19                     f[j] = min(f[j-1], f[j]) + triangle[i][j];
    20                     
    21         int ret = INT_MAX;
    22         for(int i = 0; i < f.size(); i++)
    23             ret = min(ret, f[i]);
    24             
    25         return ret;       
    26     }
    27 };
  • 相关阅读:
    sudo配置临时取得root权限
    Linux 前台 和 后台进程 说明
    延迟加载
    事件代理
    字符串方法总结
    javascript
    HTML
    通用样式,如清除浮动
    html脱离文档流事件
    经典容易忽略的行内块
  • 原文地址:https://www.cnblogs.com/chkkch/p/2772242.html
Copyright © 2011-2022 走看看