[Leetcode] 120. 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.

题目大意:给定一个三角形的二维数组,计算出从顶部到底部最小的路径之和。

思路:依次计算出到达每层节点的最短距离,到最后一层时,统计距离最小的那个。

     [2],                       【2】
    [3,4],                【5=2+3】【6=2+4】
   [6,5,7],        【11=6+5】【10=5+5】【13=7+6】
  [4,1,8,3]   【15=11+4】【11=10+1】【18=10+8】【16=13+3】
最后一层中,最小的数为11。
class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int n=triangle.size();
        if(n==0) return 0;
        vector<vector<int>> dp(1);
        dp[0].push_back(triangle[0][0]);
        for(int i=1;i<n;i++)
        {
            vector<int> tmp;
            tmp.push_back(triangle[i][0]+dp[i-1][0]);//每层第一个数
            for(int j=1;j<i;j++)
            {
                //顶部到当前节点路径和最小值为当前节点值加上上一层相邻两个数最小值
                int minTmp=triangle[i][j] + min(dp[i-1][j-1], dp[i-1][j]);
                tmp.push_back(minTmp);
            }
            tmp.push_back(triangle[i][i]+dp[i-1][i-1]);//每层最后一个数
            dp.push_back(tmp);
        }
        
        int minNum=INT_MAX;
        for(int i=0;i<dp[n-1].size();i++)//计算最后一层最小的那个数
        {
            minNum = min(minNum,dp[n-1][i]);
        }
        return minNum;
            
    }
};

注:还有更简单的方法,下次实现。

   

原文地址:https://www.cnblogs.com/hejunlin1992/p/7599723.html