【Leetcode】120. Triangle

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

AN


该题为24江南大学851所涉及的DP题型!
这里重点介绍下 min_element() 函数:
min_element()max_element()是C++标准库中的算法函数,用于查找容器中的最小值和最大值

使用方法如下:

  1. 首先引入头文件。
#include <algorithm>
  1. 调用min_element()函数,传入要查找的容器的起始迭代器和结束迭代器。
auto min = min_element(container.begin(), container.end());
  1. 调用max_element()函数,传入要查找的容器的起始迭代器和结束迭代器。
auto max = max_element(container.begin(), container.end());
  1. min_element()和max_element()函数返回的是指向最小值和最大值的迭代器,可以通过解引用操作符(*)来获取实际的值。
cout << "最小值是:" << *min << endl;
cout << "最大值是:" << *max << endl;

下面是一个完整的示例代码:

#include <iostream>
#include <vector>
#include <algorithm>

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是容器中的元素个数。如果容器中有多个最小值或最大值,函数只会返回第一个找到的位置的迭代器。如果要找到所有的最小值或最大值,可以使用循环遍历的方式来实现。

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值