您的位置:首页 > 其它

Leetcode 120 Triangle(图解)

2016-03-26 10:40 531 查看
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).

思路:1.题目中定义一个vector的vector存储Triangle,无须赘述。

 2.然后图中红色连线是最短路线的一个目前可行小部分,用一个vector数组b来存储, 并且自底向上累计(例如

对于最底下来说  b[0]=10,b[1]=13,b[2]=10,b[3]=9 (分别对应四根连线相加的值)然后依次往上累计(红线代表选择过程) 最终选择5 4 11 2 3这条路 )。



代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int minimumTotal_1(vector<vector<int> > &triangle) {
for (int i = triangle.size() - 2; i >= 0; --i)
for (int j = 0; j < i + 1; ++j)
{
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);
}
return triangle[0][0];
}
int minimun (vector<vector<int> >&triangle)
{
int sz = triangle.size();
vector<int>b = triangle[sz - 1];
for (int i = triangle.size() - 2; i >= 0; --i)
{
for (int j = 0; j < i + 1; ++j)
{
b[j] = triangle[i][j] + min(b[j], b[j + 1]);
}
}
return b[0];
}

int main()
{
vector<vector<int>>ivec{ { 3 }, { 9, 2 }, { 8, 20, 11 }, { 1, 2, 3, 4 }, { 9, 20, 11, 7, 5 } };
//cout << minimumTotal_1(ivec);
cout << minimun(ivec);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: