Triangle
2015-08-04 20:20
246 查看
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
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.
Solution:
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.
Solution:
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { int len = triangle.size(); vector<int> dp(len); dp[0] = triangle[0][0]; for(int i = 1; i < len; ++i) { int wid = triangle[i].size(); dp[wid-1] = dp[wid-2] + triangle[i][wid-1]; for(int j = wid - 2; j > 0; --j) { dp[j] = min(dp[j-1], dp[j]) + triangle[i][j]; } dp[0] += triangle[i][0]; } int minsum = dp[0]; for(int i = 0; i < len; ++i) { if(minsum > dp[i]) minsum = dp[i]; } return minsum; } };
相关文章推荐
- POJ 3468 线段树区间更新求和模板
- udev绑定ASM磁盘组
- Lua学习笔记(一):搭建开发环境
- 科技世界患上“恐美症”?
- HDOJ Avoid The Lakes (DFS)
- 旅行
- 古朴原装232转TTL,232转针,带 5V电源电路板,纯手工打造,全球仅此一套
- Lotto POJ2245【全排列问题】
- 2015 多校赛 第一场 1007 (hdu 5294)
- [MetaHook] Load large texture from model
- Android drawText获取text宽度的三种方式
- java发送邮件(3)
- 线段树模板
- HTTP请求在网络中的详细过程
- Android -- 屏幕适配
- Android ApiDemos示例解析(68):Graphics->MeasureText
- Using XILINX IP Core Block RAM (1)
- fast_nginx_module二次开发_结合imageMagick
- 多git服务器ssh秘钥配置
- HDU5351 MZL's Border