码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_120题——Triangle (动态规划)

时间:2015-05-19 10:16:34      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

Triangle

 Total Accepted: 39052 Total Submissions: 143341My Submissions

 

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.

 

Hide Tags
 Array Dynamic Programming
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

   这道题属于比较简单的动态规划那一类题,若是采用递归的思想来做就时间复杂度就太复杂了,

从下往上依次递推,欲计算上一行的最小路径,先求出它下面的最小路径

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!