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

解题思路:动态规划题,递推式为:dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j];这道题用自底向上比较容易。(自定向上需要考虑的边界问题比较多,递推式为:dp[i][j]=min(dp[i-1][j],dp[i-1][j-1])+triangle[i][j], 需要讨论 j=0 和j=i 两种特殊情况)

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

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10352894.html
今日推荐