标签:
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.
Array Dynamic Programming
这道题属于比较简单的动态规划那一类题,若是采用递归的思想来做就时间复杂度就太复杂了,
从下往上依次递推,欲计算上一行的最小路径,先求出它下面的最小路径
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int minimumTotal(vector<vector<int> > &triangle) {
int len_line=triangle.size();
vector<int> temp;
if(triangle.empty())
return 0;
if(len_line==1)
return triangle[0][0];
for(int j=0;j<len_line;j++)
temp.push_back(triangle[len_line-1][j]);
for(int i=len_line-2;i>=0;i--)
{
for(int j=0;j<=i;j++)
temp[j]=min(temp[j],temp[j+1])+triangle[i][j];
}
return temp[0];
}
int main()
{
vector<vector<int> > vec;
vector<int> vec_line;
vec_line.push_back(-1);
vec.push_back(vec_line);
vec_line.clear();
vec_line.push_back(2);
vec_line.push_back(3);
vec.push_back(vec_line);
vec_line.clear();
vec_line.push_back(1);
vec_line.push_back(-1);
vec_line.push_back(-3);
vec.push_back(vec_line);
cout<<minimumTotal(vec)<<endl;
}
leetcode_120题——Triangle (动态规划)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4513613.html