Given a triangle array, return the minimum path sum
from top to bottom.
For each step, you may move to an adjacent number
of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1
on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
Example 2:
Input: triangle = [[-10]]
Output: -10
Constraints:
1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
AC:
/*
* @lc app=leetcode.cn id=120 lang=cpp
*
* [120] 三角形最小路径和
*/
// @lc code=start
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
vector<int> f(n);
f[0] = triangle[0][0];
for(int i = 1; i < n; i++) {
f[i] = f[i - 1] + triangle[i][i];
for(int j = i - 1; j > 0; j--) {
f[j] = min(f[j - 1], f[j]) + triangle[i][j];
}
f[0] += triangle[i][0];
}
return *min_element(f.begin(), f.end());
}
};
// @lc code=end
该题为24江南大学851所涉及的DP题型!
这里重点介绍下 min_element() 函数:
min_element()
和max_element()
是C++标准库中的算法函数,用于查找容器中的最小值和最大值。
使用方法如下:
#include
auto min = min_element(container.begin(), container.end());
auto max = max_element(container.begin(), container.end());
cout << "最小值是:" << *min << endl;
cout << "最大值是:" << *max << endl;
下面是一个完整的示例代码:
#include
#include
#include
using namespace std;
int main() {
vector<int> numbers = {10, 25, 5, 15, 30, 20};
auto min = min_element(numbers.begin(), numbers.end());
auto max = max_element(numbers.begin(), numbers.end());
cout << "最小值是:" << *min << endl;
cout << "最大值是:" << *max << endl;
return 0;
}
运行结果:
最小值是:5
最大值是:30
注意,min_element()
和max_element()
函数的时间复杂度为O(n)
,其中n是容器中的元素个数。如果容器中有多个最小值或最大值,函数只会返回第一个找到的位置的迭代器。如果要找到所有的最小值或最大值,可以使用循环遍历的方式来实现。