leetcode 120. Triangle
2016-03-11 10:48
423 查看
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) {
vector<vector<int>>uppersum(triangle.size());
uppersum[0].push_back(triangle[0][0]);
for (int i = 1; i < triangle.size(); i++)
{
uppersum[i].resize(triangle[i].size());
uppersum[i][0] = uppersum[i - 1][0] + triangle[i][0];
uppersum[i].back() = uppersum[i - 1].back() + triangle[i].back();
for (int j = 1; j < triangle[i].size() - 1; j++)
{
uppersum[i][j] = triangle[i][j];
uppersum[i][j] += uppersum[i - 1][j - 1] < uppersum[i - 1][j] ? uppersum[i - 1][j - 1] : uppersum[i - 1][j];
}
}
int minsum = uppersum.back()[0];
for (int i = 1; i < triangle.back().size();i++)
if (uppersum.back()[i] < minsum)
minsum = uppersum.back()[i];
return minsum;
}
};
accepted
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) {
vector<vector<int>>uppersum(triangle.size());
uppersum[0].push_back(triangle[0][0]);
for (int i = 1; i < triangle.size(); i++)
{
uppersum[i].resize(triangle[i].size());
uppersum[i][0] = uppersum[i - 1][0] + triangle[i][0];
uppersum[i].back() = uppersum[i - 1].back() + triangle[i].back();
for (int j = 1; j < triangle[i].size() - 1; j++)
{
uppersum[i][j] = triangle[i][j];
uppersum[i][j] += uppersum[i - 1][j - 1] < uppersum[i - 1][j] ? uppersum[i - 1][j - 1] : uppersum[i - 1][j];
}
}
int minsum = uppersum.back()[0];
for (int i = 1; i < triangle.back().size();i++)
if (uppersum.back()[i] < minsum)
minsum = uppersum.back()[i];
return minsum;
}
};
accepted
相关文章推荐
- awk 用法(使用入门)
- string类的写时才拷贝(Copy-On-Write)
- C++第二次实验
- 使用selenium自动登录淘宝并获取cookie
- (六) WebService-- HttpClient 调用WS服务
- (七) WebService-- 修改WSDL文档
- 深度学习与人脸识别系列(3)__基于VGGNet的人脸识别系统
- 科大讯飞语音无限制录音、识别功能的实现:Android studio(一)
- Android开发中怎样调用系统Email发送邮件(多种调用方式)
- [转] npm 模块安装机制简介
- 复利计算1.0,2.0,3.0
- 杭电oj 1001 sum problem
- Mvc EF使用中出现LocalDB Error52的
- 快速排序
- java.lang.VerifyError: Bad <init> method call from inside of a branch
- 将GridView内嵌在ScrollView中
- Windows Embedded Standard 7 部署须知
- SAX和DOM
- IntentService简介
- welcome to mykernel