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

    Analyse: result[i][j] = min(result[i - 1][j - 1], result[i - 1][j]) + triangle[i][j];

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int minimumTotal(vector<vector<int> >& triangle) {
     4     if(triangle.size() == 0) return 0;
     5     if(triangle.size() == 1) return triangle[0][0];
     6     
     7     vector<vector<int> > result;
     8     result = triangle;
     9     
    10     for(int i = 1; i < triangle.size(); i++){
    11         for(int j = 0; j <= i; j++){
    12             if(j == 0) result[i][j] = result[i - 1][0] + triangle[i][j];
    13             else if(j == i) result[i][j] = result[i - 1][j - 1] + triangle[i][j];
    14             else result[i][j] = min(result[i - 1][j - 1], result[i - 1][j]) + triangle[i][j];
    15         }
    16     }
    17     
    18     int n = triangle.size();
    19     int path = result[n - 1][0];
    20     for(int i = 1; i < n; i++){
    21         path = min(result[n - 1][i], path);
    22     }
    23     return path;
    24 }
    25 };
  • 相关阅读:
    Comet OJ
    AtCoder Grand Contest 002题解
    AtCoder Grand Contest 001 题解
    线性基求交
    2019牛客暑期多校训练营(第四场)题解
    AtCoder Grand Contest 036题解
    计算几何 val.2
    计算几何 val.1
    模拟退火学习笔记
    动态点分治学习笔记
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4749466.html
Copyright © 2020-2023  润新知