Leetcode 题解系列(十二)
来源:互联网 发布:荣格全集 淘宝 编辑:程序博客网 时间:2024/06/08 17:03
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)
,经过该点的代价为
时间复杂度和空间复杂度为
为了方便,可以在每一行的前后各加距离为正无穷的点,简化逻辑。
代码如下:
#define MAX 1000000class 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; }};
降低空间复杂度
由于每一行只依赖于上一行的结果,所以可以进行覆盖,但要记得保存
#define MAX 1000000class 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; }};
阅读全文
0 0
- Leetcode 题解系列(十二)
- Leetcode 题解系列(一)
- Leetcode 题解系列(二)
- Leetcode 题解系列(三)
- Leetcode 题解系列(四)
- Leetcode 题解系列(五)
- Leetcode 题解系列(六)
- Leetcode 题解系列(七)
- Leetcode 题解系列(八)
- Leetcode 题解系列(九)
- Leetcode 题解系列(十)
- Leetcode 题解系列(十一)
- Leetcode 题解系列(十三)
- LeetCode OJ题解系列
- LeetCode刷题系列(十二)Quick Questions
- LeetCode Single Number系列题解
- LeetCode题解系列--1. Two Sum
- LeetCode题解系列--5. Longest Palindromic Substring
- 查看Nginx、apache、MySQL和PHP的编译参数
- keil5 STM32 浮点数转字符串跑飞
- 好接口的设计与实现
- keil STM32 hex转浮点数及浮点数转字符串较好方案
- STL_Lesson005_001
- Leetcode 题解系列(十二)
- 戴尔7447 win10安装Ubuntu双系统
- HQL补充知识点
- 测试通过HTTP请求依赖其它服务的系统
- Keil5无法使用Jlink
- STL_Lesson005_002
- 服务读写不分离架构
- 哈希函数(散列函数)详解
- 6---------prim算法的简单应用