LeetCode_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.
分析:This problem is more likely to be a (dynamic programming) DP problem,
where a[n][i] = a[n][i]+min(a[n-1][i], a[n-1][i-1]).
Note that in this problem, "adjacent" of a[i][j] means a[i-1][j] and a[i-1][j-1], if available(not out of bound), while a[i-1][j+1] is not "adjacent" element.
The minimum of the last line after computing is the final result.
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = triangle.size();
for( int i = ; i< len ; i++)
for( int j = ; j < triangle[i].size(); j++){
if(j == ){
triangle[i][j] += triangle[i-][j];
continue;
}
if(j == triangle[i].size() -){
triangle[i][j] += triangle[i-][j-];
continue;
}
int val = triangle[i-][j] < triangle[i-][j-] ? triangle[i-][j]
:triangle[i-][j-] ;
triangle[i][j] += val;
} int minval = triangle[len-][]; for(int i = ; i< triangle[len-].size() ; i++){
if(minval > triangle[len-][i] ) minval = triangle[len-][i];
} return minval;
}
};
reference :http://yucoding.blogspot.com/2013/04/leetcode-question-112-triangle.html
LeetCode_Triangle的更多相关文章
随机推荐
- Codeforces 437E The Child and Polygon
http://codeforces.com/problemset/problem/437/E 题意:求一个多边形划分成三角形的方案数 思路:区间dp,每次转移只从一个方向转移(L,R连线的某一侧),能 ...
- NSIS脚本调用C语言写的插件
其实NSIS的官网已经提供了很多别人开发的插件了,今天需要用到GetVersion这个插件,这是不维护的插件了,不推荐用,但是由于现实中的问题,导致我不得不用这个插件. 所以就下载下来了. 下载下来之 ...
- [转]一步步搭建Ubuntu环境——dpkg 被中断,您必须手工运行 sudo dpkg --configure -a 解决此问题——安装Flashplayer出错 ------不错
原文网址:http://blog.csdn.net/xuezhimeng2010/article/details/8545261 解决方法如下: sudo rm /var/cache/apt/arch ...
- bzoj2929 [Poi1999]洞穴攀行
Description 一队洞穴学者在Byte Mountain的Grate Cave里组织了一次训练.训练中,每一位洞穴学者要从最高的一个室到达最底下的一个室.他们只能向下走.一条路上每一个连续的室 ...
- apache2 httpd 基于域名的虚拟主机配置 for centos6X 和debian-8
全系统虚拟主机: for debian 系统的apache2 域名 虚拟主机
- 传阿里整合资源,进军O2O市场
阿里巴巴对于本地生活市场,以及O2O领域始终虎视眈眈.从最早的融合口碑网,到最近阶段推出淘宝点点.收购高德地图等一系列app产品,其整合线上线下消费市场的野心已十分明显. 今年年初,阿里巴巴集团重新进 ...
- IOS 缩放图片常用方法
/** * 指定Size压缩图片 (图片会压缩变形) * * @param image 原图 * @param size 压缩size * * @return 压缩后的图片 */ -(UIImage* ...
- XPath详解
xPath技术 1 引入 问题:当使用dom4j查询比较深的层次结构的节点(标签,属性,文本),比较麻烦!!! 2 xPath作用 主要是用于快速获取所需的节点对象. 3 在dom4j中如何使用 ...
- [RxJS] Stopping a Stream with TakeUntil
Observables often need to be stopped before they are completed. This lesson shows how to use takeUnt ...
- crtmpserver通常使用基本类演示
以前我们做了分析过程,这一次,我们都参与了类做梳子,两个可以一起关注一下一起合并,整个方案的实施是有帮助. BaseClientApplication APP基类,一切APP都基于这个类 Stream ...