【一天一道LeetCode】#120. Triangle

时间:2023-03-09 00:19:50
【一天一道LeetCode】#120. Triangle

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:给定一个三角矩阵,求从上到下的路径中和最小的路径。每次向下走只能从相邻的数走。

解题思路:Note中提到空间复杂度要为O[n],n为最下面一行数的个数

这种问题一般都会想到动态规划,所以直接往转移方程上想。

记dp[i][j]为(i,j)点到最低端的最小路径和。n为矩阵的深度

则从第n-1行开始,dp[i][j] += min(dp[i+1][j],dp[i+1][j+1]),一路往上计算,最终dp[0][0]即为所求。

于是很快写出代码,10msAC版本。

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.empty()) return 0;
        vector<vector<int>> dp = triangle;
        int n = dp.size();
        if(n==1) return triangle[0][0];//只有一行的时候直接返回
        for(int i = n-2 ; i >=0 ; i--)
        {
            for(int j = 0 ; j < dp[i].size();j++)
            {
                dp[i][j] += min(dp[i+1][j],dp[i+1][j+1]);//状态转移方程
            }
        }
        return dp[0][0];
    }
};

考虑到优化上述代码,使得空间复杂度更低,满足O(n),其实,只用一个一维数组就能解决问题。

下面的代码时优化后的版本,8msAC.

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        if(triangle.empty()) return 0;
        int n = triangle.size();
        vector<int> dp = triangle[n-1];//空间复杂度更低
        for(int i = n-2 ; i >=0 ; i--)
        {
            for(int j = 0 ; j < triangle[i].size();j++)
            {
                dp[j] = triangle[i][j]+min(dp[j],dp[j+1]);
            }
        }
        return dp[0];
    }
};