LeetCode之“动态规划”:Triangle
2024-08-24 20:59:06
题目要求:
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
[
[],
[,],
[,,],
[,,,]
]
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.
具体代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int rows = triangle.size();
if(rows == )
return ; int * dp = new int[rows];
int szOfLastRow = triangle[rows - ].size();
for(int i = ; i < szOfLastRow; i++)
dp[i] = triangle[rows - ][i]; for(int i = rows - ; i > -; i--)
{
int cols = triangle[i].size();
for(int j = ; j < cols; j++)
dp[j] = triangle[i][j] + min(dp[j], dp[j + ]);
} return dp[];
}
};
这个程序中最核心的地方在:
dp[j] = triangle[i][j] + min(dp[j], dp[j + ]);
可以用图表示如下:
其中一个例子就是:
需要注意的就是这个例子中只改变的是dp[0],dp[1]并没有改变。
最新文章
- [LeetCode] Maximum Subarray 最大子数组
- MVC 知识点学习3(linq to sql)
- 黄聪:GeckoFX如何引用jquery文件并执行自定义JS
- 从多个XML文档中读取数据用于显示webapi帮助文档
- SQL Server 2014新特性——Buffer Pool扩展
- CentOS 6.6 yum 搭建LAMP环境
- Mysql auto_increment 重新计数(让id从1开始)
- 基于WebForm和Bootstrap的权限框架解决方案 一.PQGRID的使用
- [leetcode-625-Minimum Factorization]
- red5 自定义文件存放目录
- Myeclipse xml标签代码提示,引入schema
- 学习了解CyclicBarrier
- es6(一)
- redis操作(String,Hash,List,Set,其他操作)
- python 全栈开发,Day64(视图,触发器,函数,存储过程,事务)
- 【ORA错误大全】 ORA-19527
- 关于 OpenIdConnect 认证启用 HTTPS 回调 RedirectUri 不生效问题
- hdu 6395 Sequence (简单矩乘)
- Oracle VM VirtualBox 虚拟机 常用快捷键
- 【MYSQL权限】数据库权限部署
热门文章
- React Native组件只Image
- x264源代码简单分析:x264命令行工具(x264.exe)
- java详解final、多态、抽象类、接口原理
- FFmpeg源代码简单分析:libswscale的sws_getContext()
- Cocos2D瓦块地图高清屏(retina)显示比例问题的解决
- android orm持久层框架
- FFmpeg示例程序合集-Git批量获取脚本
- Dynamics CRM 电子邮件服务器配置文件Advanced配置中关闭SSL
- Android开发学习之路--Notification之初体验
- Web开发技术的演变