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

思路:

典型的动态规划,从上到下,或者采用递推的方法。具体的公式就是  num[i][j] = max(num[i-1][j+1],num[i-1][j])+nums[i][j];

意思就是:当前的数值,等于其下方和下面右边一个的最大值加上当前数字数值。

采用一个循环即可达到目的。

代码:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int m=triangle.size();
        int dp[m][m];
        
        for(int i=0;i<m;i++){
            dp[m-1][i]=triangle[m-1][i];
        }
        
        for(int i=m-2;i>=0;i--){
            for(int j=0;j<=i;j++){
                dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j];
            }
        }
        
        return dp[0][0];
    }
};


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519857.html