[LeetCode] Triangle
2015-08-12 17:11
357 查看
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.
解题思路:
动态规划。用d来记录从根到页的最短路径,i为当前行数。则有
d[j] = d[j-1] + triangle[i][j],j==i时
d[j] = d[0] + triangle[i][0], j==0时
d[j] = min(d[j-1], d[j]) + triangle[i][j],其他。
注意计算d[j]时,会用到上一次的d[j-1],因此可以按d[i..0]的顺序来计算。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
if(n==0){
return 0;
}
if(n==1){
return triangle[0][0];
}
int d
;
d[0] = triangle[0][0];
for(int i=1; i<n; i++){
for(int j=i; j>=0; j--){ //这里从由高到低
if(j==i){
d[j] = d[j-1] + triangle[i][j];
}else if(j==0){
d[j] = d[0] + triangle[i][0];
}else{
d[j] = min(d[j-1], d[j]) + triangle[i][j];
}
}
}
int minPath = d[0];
for(int i=1; i<n; i++){
minPath = min(d[i], minPath);
}
return minPath;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解