Leetcode Week15 Triangle

Question

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.

Answer

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

  动态规划问题。

猜你喜欢

转载自www.cnblogs.com/thougr/p/10207103.html
今日推荐