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的更多相关文章
随机推荐
- ultraedit删除空行(含空格,tab,制表符等怪字符)
打开ultraedit,ctrl+r弹出替换对话框,点选启用正则表达式 在查找框输入 ^p^p 在替换框输入 ^p 仍有部分空行还在,继续处理: 查找框中输入:%[ ^t]++^p,注意^t之前有空 ...
- .net 开发必备小抄(电子书)
http://www.syncfusion.com/resources/techportal/ebooks/accountinghttp://www.syncfusion.com/resources/ ...
- Linux 让进程在后台可靠运行的几种方法
我们经常会碰到这样的问题,用 telnet/ssh 登录了远程的 Linux 服务器,运行了一些耗时较长的任务, 结果却由于网络的不稳定导致任务中途失败.如何让命令提交后不受本地关闭终端窗口/网络断开 ...
- 关于overload和override
override 覆盖,表示在子类中一个函数覆盖基类中的同名函数,或者局部的某个函数覆盖了全局的某个同名函数.被覆盖的函数通常不能直接被调用,必须借助一些显式的强制手段. overload 重载,表示 ...
- java 实例化是调用了子类重写方法
java 实例化时调用了抽象方法或者class里面某个方法,如果子类有重写改方法,实际运行的是子类重写方法 package auto.test; //抽象父类 public abstract clas ...
- html--鼠标控制DIV移动
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- python使用一个集合代替列表
"""说明:对于一个指定的序列,如果需要获得一个只包含该序列中不重复的序列时,使用以下算法:"""seq=['a','a','b','c', ...
- Laravel-表单篇-零散信息
1.asset('path'):用于引入静态文件,包括css.js.img 2.分页,调用模型的paginate(每页显示的行数)方法, 如$student = Student::paginate(2 ...
- POJ2151Check the difficulty of problems 概率DP
概率DP,还是有点恶心的哈,这道题目真是绕,问你T个队伍.m个题目.每一个队伍做出哪道题的概率都给了.冠军队伍至少也解除n道题目,全部队伍都要出题,问你概率为多少? 一開始感觉是个二维的,然后推啊推啊 ...
- C++刷称号——2707: 素数与要素
Description 从键盘输入的随机整数n,如果n不是质数,然后计算n所有的因素(不含1).例如,对于16,出口2,4,8:否则输出"It is a prime number." ...