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的更多相关文章
随机推荐
- 文件锁及其实例,底层文件I/O操作,基本文件操作和实例,Linux中文件及文件描述符概述
http://blog.csdn.net/rl529014/article/details/51336161 http://blog.csdn.net/rl529014/article/details ...
- Linux 让进程在后台可靠运行的几种方法
我们经常会碰到这样的问题,用 telnet/ssh 登录了远程的 Linux 服务器,运行了一些耗时较长的任务, 结果却由于网络的不稳定导致任务中途失败.如何让命令提交后不受本地关闭终端窗口/网络断开 ...
- VMware Workstation 精致汉化系列 使用方法
http://kuai.xunlei.com/d/QqGABAKChQBwMzxR983 迅雷快传 XP系统之家-温馨提示: VMware Workstation 精致汉化系列 使用方法:1.安装 ...
- bzoj3039 玉蟾宫
Description 有一天,小猫rainbow和freda来到了湘西张家界的天门山玉蟾宫,玉蟾宫宫主蓝兔盛情地款待了它们,并赐予它们一片土地.这片土地被分成N*M个格子,每个格子里写着'R'或者' ...
- log4j 突然不打印记录,提示:No appenders could be found for logge,处理方法
log4j 一直都在使用正常,log4j.xml配置.代码都没有修改,突然不打印记录,出现下面提示: log4j:WARN No appenders could be found for logger ...
- windows 查看端口被占用
C:\Users\xxxx> 根据端口找到进程14716 C:\Users\xxxx>tasklist|findstr "14716"node.exe 14716 Co ...
- 去掉MySQL字段中的空格
mysql replace 函数 语法:replace(object,search,replace) 意思:把object中出现search的全部替换为replace 案例: SQL Co ...
- 使用代码自定义UIView注意一二三
文/CoderAO(简书作者)原文链接:http://www.jianshu.com/p/68b383b129f9著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 当一撮样式一样的视图在 ...
- Java中日期时间API小结
Java中为处理日期和时间提供了大量的API,确实有把一件简单的事情搞复杂的嫌疑,各种类:Date Time Timestamp Calendar...,但是如果能够看到时间处理的本质就可以轻松hol ...
- 多余的Using Namespaces或引用会影响程序的执行效率么?(转)
转自:http://www.cnblogs.com/Interkey/p/UsingNameSpace.html 多余的Using Namespaces或引用会影响程序的执行效率么? 在.NET程序编 ...