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

思路

二维空间压缩到一维。注意边界处理,pad了一维,可以不用判断边界。先写了二维,然后改成一维的。

代码

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

刚才在家感受到了地震。

发布了243 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104380258