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.

题目分析
动态规划

由于到达点[i, j]的路径必须经过点[i - 1, j - 1]或者点[i - 1, j],假设到达点[i, j]的最小路径为dp(i, j),经过该点的代价为 Ci,j ,那么有:

dp(i,j)=Ki,j,dp(i1,j)+Ki,j,dp(i1,j1)+Ki,j,min{dp(i1,j),dp(i1,j1)},i = 0j = 0j = iothers

时间复杂度和空间复杂度为 O(N2)
为了方便,可以在每一行的前后各加距离为正无穷的点,简化逻辑。
代码如下:


#define MAX 1000000
class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int depth = triangle.size();
        if (depth == 0) return 0;
        int width = triangle[depth - 1].size();
        vector<vector<int>> dp;
        dp.push_back({MAX, triangle[0][0], MAX});
        for (int i = 1; i < depth; ++i) {
            dp.push_back(vector<int>(i + 3, MAX));
            for (int j = 1; j <= i + 1; ++j) {
                dp[i][j] = std::min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j - 1];
            }
        }
        int min = 1000000;
        for (const auto& i: dp[depth - 1]) {
            if (min > i) min = i;
        }
        return min;
    }
};
降低空间复杂度

由于每一行只依赖于上一行的结果,所以可以进行覆盖,但要记得保存 dp(i1,j1)


#define MAX 1000000
class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int depth = triangle.size();
        if (depth == 0) return 0;
        int width = triangle[depth - 1].size();
        vector<int> dp(width + 2, MAX);
        dp[1] = triangle[0][0];
        int min = MAX;
        for (int i = 1; i < depth; ++i) {
            int prev = dp[0];
            for (int j = 1; j < i + 2; ++j) {
                int tmp = dp[j];
                dp[j] = std::min(dp[j], prev) + triangle[i][j - 1];
                prev = tmp;
            }
        }
        for (const auto& i: dp) {
            if (min > i) min = i;
        }
        return min;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值