题源:LeetCode

链接:https://leetcode-cn.com/problems/triangle/

 

三角形最小路径和_动态规划

 

 

这道题目使用动态规划解决。

三角形最小路径和_其他_02

 

 三角形最小路径和_其他_03

 

 



1 class Solution {
2 public:
3 int minimumTotal(vector<vector<int>>& triangle) {
4 int n = triangle.size();
5 vector<vector<int>> f(n, vector<int>(n));
6 f[0][0] = triangle[0][0];
7 for (int i = 1; i < n; ++i) {
8 f[i][0] = f[i - 1][0] + triangle[i][0];
9 for (int j = 1; j < i; ++j) {
10 f[i][j] = min(f[i - 1][j - 1], f[i - 1][j]) + triangle[i][j];
11 }
12 f[i][i] = f[i - 1][i - 1] + triangle[i][i];
13 }
14 return *min_element(f[n - 1].begin(), f[n - 1].end());
15 }
16 };