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的更多相关文章

随机推荐

  1. ResourceString的用法

    在Delphi编程的那段“古老”的日子里(就是在版本4之前),在程序中使用字符串有两个基本的方法.你可以使用字符串将它们嵌入到源程序中,例如: MessageDlg( 'Leave your stin ...

  2. (转)PHP zval内存回收机制和refcount_gc和is_ref_gc

    出处 : http://blog.sina.com.cn/s/blog_75a2f94f0101gygh.html 对于PHP这种需要同时处理多个请求的程序来说,申请和释放内存的时候应该慎之又慎,一不 ...

  3. CSS flex让所有灵活的项目都带有相同的长度,忽略它们的内容:

    .flexbox {     display: -webkit-box;     display: -webkit-flex;     display: -ms-flexbox;     displa ...

  4. FreeBsdb FAMP Lamp环境

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1IAAAHlCAIAAABwFFq0AAAgAElEQVR4nO3d23WruhYA0JTmciiGTm

  5. Android驱动之 Linux Input子系统之TP——A/B(Slot)协议

    将A/B协议这部分单独拿出来说一方面是因为这部分内容是比较容易忽视的,周围大多数用到input子系统的开发人员也不甚理解:另一方面是由于这部分知识一旦扩展到TP(触摸屏Touch Panel)的多点触 ...

  6. RequireJS入门(二)

    上一篇是把整个jQuery库作为一个模块.这篇来写一个自己的模块:选择器. 为演示方便这里仅实现常用的三种选择器id,className,attribute.RequireJS使用define来定义模 ...

  7. 一个js编写全选、弹出对话框、ajax-json的案例

    js功能有:全选.弹出对话框.使用json传输ajax数据:不想在写多余的文字了,直接上代码: <%@ page language="java" contentType=&q ...

  8. CFGYM 2013-2014 CT S01E03 D题 费用流模版题

    题意: n行, a房间的气球,b房间的气球 i行需要的气球,与a房的距离,b房的距离 求最小距离 #include <stdio.h> #include <string.h> ...

  9. read(),write() 读/写文件

    read read()是一个系统调用函数.用来从一个文件中,读取指定长度的数据到 buf 中. 使用read()时需要包含的头文件: <unistd.h> 函数原型: ssize_t re ...

  10. Oracle - SQL 错误: ORA-00917: 缺失逗号

    ORACLE SQL语句中int型插入数据库时,不要加引号.