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. BZOJ2212: [Poi2011]Tree Rotations

    2212: [Poi2011]Tree Rotations Time Limit: 20 Sec  Memory Limit: 259 MBSubmit: 391  Solved: 127[Submi ...

  2. Android 状态栏通知Notification、NotificationManager简介

    Notification(通知)一般用在电话,短信,邮件,闹钟铃声,在手机的状态栏上就会出现一个小图标,提示用户处理这个通知,这时手从上方滑动状态栏就可以展开并处理这个通知: 在Android系统中, ...

  3. C++ int 转换成 string intToString

    string intToString(int num) { stringstream ss; ss<<num; return ss.str(); } 一个简单的小例子. #include ...

  4. Dynamic Binding & Static Binding

    Reference: JavaPoint BeginnerBook What is Binding Connecting a method call to the method body is kno ...

  5. HDU 3265 Posters(线段树)

    HDU 3265 Posters pid=3265" target="_blank" style="">题目链接 题意:给定一些矩形海报.中间有 ...

  6. DIV 与 Table 嵌套

    当然可以了.对于DIV定义表示一块可显示 HTML 的区域. Specifies a container that renders HTML. 注释此元素在 Internet Explorer 3.0 ...

  7. C#基础:命令解析

    1.普通格式命令的解析 例如: RENA<SP>E:\\A.txt<SP>C:\\B.txt<CRLF> (SP -> 空格,CRLF -> 回车加换行 ...

  8. mysql 5.6 设置慢查询

    mysql 5.6 开启慢查询日志 slow_query_log = on #开启慢查询 1 或者 on long_query_time = 3 #记录超过的时间,单位是秒,默认是10s slow_q ...

  9. Javascript基础引用类型之Object

    虽然说ECMAScript也是一门对象语言,但是它和其他面向对象语言还是有区别的,它不具有类和接口等基本结构.所以在ECMAScript中一般说类指的是引用类型.创建Object实例的方式有两种: 第 ...

  10. Android SQLite API的使用(非原创)

    1.使用SQLite的API来进行数据库的添加.删除.修改.查询 package com.example.sqlitedatabase.test; import android.content.Con ...