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;
}
本文介绍了一种求解从三角形顶部到底部的最小路径和的问题,通过自底向上的动态规划方法,逐步计算出每一步的最优解,最终得到整个三角形的最小路径总和。

被折叠的 条评论
为什么被折叠?



