Question:
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).
Answer:
//本题我的解法是利用树的递归。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
return min(triangle, 0, 0);
}
int min(vector<vector<int>> &triangle, int level, int i)
{
if(level == triangle.size()-1)
{
return triangle[level][i];
}
else
{
int left = min(triangle, level + 1, i);
int right = min(triangle, level + 1, i+1);
return left<right?(left+triangle[level][i]):(right+triangle[level][i]);
}
}
};
Run Code Result:
Your input
[[2], [3,4], [6,5,7]]
Your answer
10
Expected answer
10
本文介绍了一种使用递归算法解决寻找三角形从顶到底最小路径和的问题,并给出了一段C++实现代码示例。
5128

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



