leetcode-120-线性DP-三角形最小路径和 发表于 2020-04-14 | 分类于 数据结构与算法 题目 解法1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374// 动态规划 空间复杂度O(n^2)// 自顶向下求解class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); if(triangle.empty()) return 0; if(n == 1) return triangle[0][0]; // dp[i][i] = x 表示走到第i行第j列时的最小路径和 vector<vector<int>> dp(n, vector<int>(n, -1)); dp[0][0] = triangle[0][0]; for(int i = 1; i < n; ++i){ for(int j = 0; j <= i; ++j){ if(j == 0) dp[i][j] = dp[i-1][j] + triangle[i][j]; else if(j == i) dp[i][j] = dp[i-1][j-1] + triangle[i][j]; else dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]; } } return *min_element(dp[n-1].begin(), dp[n-1].end()); }};// 动态规划 空间复杂度O(n^2)// 自底向上求解class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); if(triangle.empty()) return 0; if(n == 1) return triangle[0][0]; // 自底向上,先初试化最后一行 // dp[i][i] = x 表示走到第i行第j列时的最小路径和 vector<vector<int>> dp(n, vector<int>(n, -1)); dp[n-1] = triangle[n-1]; for(int i = n-2; i >= 0; --i){ for(int j = 0; j <= i; ++j){ dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + triangle[i][j]; } } return dp[0][0]; }};// 动态规划 空间复杂度O(n)// 自底向上求解class Solution {public: int minimumTotal(vector<vector<int>>& triangle) { int n = triangle.size(); if(triangle.empty()) return 0; if(n == 1) return triangle[0][0]; // 自底向上求解,dp保存最后一行数值,然后逐次向上求解 vector<int> dp(triangle.back()); for(int i = n-2; i >= 0; --i){ for(int j = 0; j <= i; ++j){ dp[j] = min(dp[j], dp[j+1]) + triangle[i][j]; } } return dp[0]; }};