leetcode120 Triangle
来源:互联网 发布:国事访问知乎 编辑:程序博客网 时间:2024/05/31 19:41
题目
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.
分析
题目的要求是找出在给出的三角形里找出一条从上到下的和最小的路径。
同别的动态规划的题目一样,只需要给出状态转移方程即可。
观察到,无论哪一条路径,最后一个元素总是最底层的某一个数,因此,可以通过构建一个结果数组result。
result[i][j] 表示每一条以triangle[i][j] 为最后一个元素的最小和路径,同时,可以给出状态转移方程如下:
result[i][j] = min(result[i - 1][j], result[i - 1][j - 1]) + triangle[i][j]; //此时i > 0 && j != 0 && j != iresult[i][0] = result[i - 1][0] + triangle[i][0];result[i][i] = result[i - 1][i - 1] + triangle[i][i];
但是这样在空间上的花费太大了,达到了O(n^2),题目的要求是O(n)的空间复杂度,观察状态转移方程,可以发现,每一个新状态只依赖上一层的状态信息,因此,可以只存储上一层的信息来完成状态转移。
定义result结果数组,result[j] 表示以当前迭代的行数的第j个数作为路径的最后元素的最小和路径。
因此,可以将状态转移方程改变如下:
result[j] = min(result[j - 1], result[j]) + triangle[i][j]; //i表示当前迭代到的行数,且此时j != 0 && j != i && i > 0result[0] = result[0] + triangle[i][0]; //j == 0result[i] = result[i - 1] + triangle[i][i];
代码:
class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); if (n == 0) return 0; vector<int> result(n, triangle[0][0]); for (int i = 1; i < n; i++) { result[i] = result[i - 1] + triangle[i][i]; for (int j = i - 1; j > 0; j--) { result[j] = min(result[j - 1], result[j]) + triangle[i][j]; } result[0] = result[0] + triangle[i][0]; } return *min_element(result.begin(), result.end()); }};
运行结果
- LeetCode120:Triangle
- LeetCode120. Triangle
- leetcode120. Triangle
- LeetCode120 Triangle
- leetcode120 triangle
- leetcode120 Triangle
- LeetCode120——Triangle
- leetcode120-Triangle-解题报告
- LeetCode120—Triangle
- LeetCode120. Triangle 动态规划
- Leetcode120 Triangle (第八周作业)
- leetcode120
- Leetcode120: 3Sum
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- java二维数组
- 云星数据---Scala实战系列(精品版)】:Scala入门教程022-Scala实战源码-Scala 多态01
- vue 循环出来的数据不能记录长度
- oracle 系统表空间满了
- 9. 面向对象 -- 多态、抽象、接口
- leetcode120 Triangle
- hrbust 病毒 并查集
- 判断二叉树是否是搜索二叉树和完全二叉树
- css设置元素水平垂直居中的方法
- eclipse如何重新编译项目
- Go Eclipse插件
- Hadoop之HDFS文件操作
- leetcode 134. Gas Station
- mt6735 “提示音和通知”中试听手机铃声时来电,来电铃声和预览铃声声音重叠