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; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- for循环之求质数
- 【微信】未关注公众号授权获取基本信息(头像昵称等)
- 【树状数组】hdu 4911 Inversion(离散化+树状数组求逆序数)
- svn提交问题--Commit blocked by pre-commit hook(exit code 1)with output:
- 关于正则表达式的“\b”
- LeetCode
- 1874222.html
- POJ 2594 Treasure Exploration(最小路径覆盖+Floyd求传递闭包)
- meavn建立
- Linux截图、查看图片
- 南阳理工ACM 题目21 三个水杯 java代码 广度优先
- 图文详解java内存回收机制
- Jupyter安装r内核
- android与h5之间的互调