1. 程式人生 > >LeetCode-120-Triangle

LeetCode-120-Triangle

code 問題 umt 定向 owin etc 情況 spa row

算法描述:

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]; }

LeetCode-120-Triangle