LeetCode

来源:互联网 发布:淘宝运营工资高吗 编辑:程序博客网 时间:2024/05/16 04:05

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.

求一条最短的路径,一个dp。思路还是很好想的,每次取上两个数中最小的那个。设矩阵有m行n列。

dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]    时间复杂度O(mn),空间复杂度O(mn)

因为每次只用到了两行,所以空间复杂度还可以降。dp[i] = min(dp[i], dp[i-1]) + triangle[i][j]   空间复杂度O(n)。正着更新会影响后面的值,所以选择倒着更新。

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        int m = triangle.size();        vector<int> ans(triangle[m-1].size(), 0x3f3f3f3f3f3f3f3f);        ans[0] = triangle[0][0];        for (int i = 1; i < m; ++i) {            for (int j = triangle[i].size() - 1; j >= 0; --j) {                if (j == 0) ans[j] += triangle[i][j];                else                    ans[j] = min(ans[j], ans[j-1]) + triangle[i][j];            }        }        int res = INT_MAX;        for (int i = 0; i < triangle[m-1].size(); ++i) {            res = min(res, ans[i]);        }        return res;    }};