原题链接:Leetcode 120. 三角形最小路径和
class Solution {
public:int minimumTotal(vector<vector<int>>& triangle) {int n = triangle.size();if (n == 1)return triangle[0][0];int dp[n][n];dp[0][0] = triangle[0][0];int res = INT_MAX;for (int i = 1; i < n; i++) {for (int j = 0; j < i + 1; j++) {if (j < i)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];if (j - 1 >= 0)dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + triangle[i][j]);if (i == n - 1)res = min(res, dp[i][j]);}}return res;}
};
空间优化:
dp[j]是指上一层的每j列的最小路径和
class Solution {
public:int minimumTotal(vector<vector<int>>& triangle) {int n = triangle.size();if (n == 1)return triangle[0][0];int dp[n];dp[0] = triangle[0][0];int res = INT_MAX;for (int i = 1; i < n; i++) {for (int j = i; j > 0; j--) {if (j < i)dp[j] = min(dp[j], dp[j - 1]) + triangle[i][j];else if (j == i)dp[j] = dp[j - 1] + triangle[i][j];if (i == n - 1)res = min(res, dp[j]);}dp[0] = dp[0] + triangle[i][0];}return min(res, dp[0]);}
};