LeetCode120——Triangle
2015-08-13 20:32
344 查看
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
The minimum path sum from top to bottom is
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.
实现:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
for (int i=n-2; i >=0; i--) {
for (int j = 0; j < triangle[i].size(); j++) {
triangle[i][j] += triangle[i+1][j] < triangle[i+1][j+1] ? triangle[i+1][j] : triangle[i+1][j+1];
}
}
return triangle[0][0];
}
};
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.
实现:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
for (int i=n-2; i >=0; i--) {
for (int j = 0; j < triangle[i].size(); j++) {
triangle[i][j] += triangle[i+1][j] < triangle[i+1][j+1] ? triangle[i+1][j] : triangle[i+1][j+1];
}
}
return triangle[0][0];
}
};
相关文章推荐
- uva 140 剪枝搜索
- 一般函数指针和类的成员函数指针
- android-将系统和应用程序级的屏幕亮度
- UBI介绍
- C语言经典著作
- 旋转数组的最小数字
- POJ 2955 brackets
- 关于 android receiver
- 头文件为什么要加#ifndef #define #endif
- 基于AppDomain的"插件式"开发
- java获得自己本机的外网ip(通过代理服务器)
- cygwin下编译Java出现软件包net.tinyos.message不存在错误
- HDU 5389 Zero Escape(2015年多校联合第八场 动态规划)
- Flatten Binary Tree to Linked List
- 读系统论的一点思考
- Uva 1291 Dance Dance Revolution
- 修改linux文件最大句柄数
- 导航控制器---UINavigationController
- LeetCode:Partition List
- Android (Service、BroadcastReceiver)