93:Triangle
来源:互联网 发布:淘宝店铺有几个橱窗 编辑:程序博客网 时间:2024/04/26 18:20
题目: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.
题目详情见 https://leetcode.com/problems/triangle/#/description
解析1 :自顶向下,令
但是需要注意当 j 为 第 i 行的第一个元素时,
当 j 为第 i 行的最后一个元素时,
则从顶部到底部的最小路径和为
代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(n)// 自顶向下class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { const int n = triangle.size(); vector<int> f(n, 0); // f 表示顶部元素到某一行各个位置的最小距离 f[0] = triangle[0][0]; // f[0] 的初值 for (int i = 0; i < triangle.size() - 1; ++i) { // 根据顶部元素到第 i 行各个位置的最小距离 // 推断出 到 i + 1 行各个位置的最小距离。 int last_index = triangle[i + 1].size() - 1; // 逆序搜索 triangle 中第 i+1 行的各个元素 for (int j = last_index; j >= 0; --j) { if (j == 0) f[j]= f[j] + triangle[i + 1][j]; else if (j == last_index) f[j] = f[j - 1] + triangle[i + 1][j]; else f[j] = min(f[j - 1], f[j]) + triangle[i + 1][j]; } } int min_sum = f[0]; for (int i = 1; i < f.size(); ++i) min_sum = min(min_sum, f[i]); return min_sum;};
解析2:自底向上,令
则显然易见,从顶部到底部的最小路径和为
相比如自顶向下,自底向上方法代码更为紧凑和简洁,因为不需要进行分类讨论,代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(n)// 自底向上,相比如自顶向下,代码更为紧凑简洁class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { const int n = triangle.size(); // f 表示从最底行各个位置到 triangle 中某一行各个位置的最小距离 // f 的初始值为最底行的元素 vector<int> f(triangle[n - 1].begin(), triangle[n - 1].end()); for (int i = triangle.size() - 1; i > 0; --i) { // 根据最低行各个位置到第 i 行的各个位置最小距离 // 推出到第 i-1 行的各个位置最小距离 int last_index = triangle[i - 1].size() - 1; for (int j = 0; j <= last_index; ++j) f[j] = min(f[j], f[j + 1]) + triangle[i - 1][j]; } return f[0]; }};
- 93:Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- python requests post多层字典问题
- 数据倾斜处理方法
- 7.jsp原理 指令 脚本
- 《程序设计实践》有趣的句子
- stl优化-3
- 93:Triangle
- linux下非root用户安装软件入门
- 51nod-沙拉酱前缀(二分+打表)
- caffe 06 win10 运行examples的imagenet测试用例
- Linux工作管理与系统资源查看详解
- sed命令
- python3下使用cv2.imwrite存储带有中文路径图片
- 回归树,Gradient Boosting和GBDT
- Java拾遗1:Java反射机制