Cover image for LeetCode Daily Question P120: Triangle Minimum Path Sum

LeetCode Daily Question P120: Triangle Minimum Path Sum


Timeline

Timeline

2025-09-25

init

Dynamic Programming

Problem:

Suppose dp[i][j] represents the minimum path sum starting from the (i+1)-th row and (j+1)-th column.

  • When j!=0 && j!=i

    dp[i][j]=min(dp[i1][j1]+dp[i1][j])+triangle[i][j] dp[i][j] = min(dp[i-1][j-1] + dp[i-1][j]) + triangle[i][j]

  • When j==0

    dp[i][j]=dp[i1][0]+triangle[i][j]dp[i][j] = dp[i-1][0] + triangle[i][j]

  • When j==i

    dp[i][j]=dp[i1][j1]+triangle[i][j]dp[i][j] = dp[i-1][j-1] + triangle[i][j]

    Actually, a one-dimensional array is sufficient for dp in this problem. After each level is computed, it is no longer needed, so the previous level can be overwritten.
123456789101112131415161718192021222324252627282930313233343536373839
#include <climits>#include <vector>using std::vector;class Solution {    public:        int minimumTotal(vector<vector<int> > &triangle)        {                int n = triangle.size();                int min = INT_MAX;                vector<vector<int> > dp(n, vector<int>(n));                // dp[i][j] represents the minimum value starting from the (i+1)-th row and (j+1)-th column.                // When j!=0 && j!=i                // dp[i][j] = min {dp[i-1][j-1] + dp[i-1][j]} + triangle[i][j]                // When j==0, dp[i][j] = dp[i-1][0] + triangle[i][j]                // When j==i, dp[i][j] = dp[i-1][j-1] + triangle[i][j]                dp[0][0] = triangle[0][0];                // Start from the second row, i.e., i==1                for (int i = 1; i < n; i++) {                        for (int j = 0; j <= i; j++) {                                if (j == 0) {                                        dp[i][j] = dp[i - 1][0] + triangle[i][j];                                } else if (j == i) {                                        dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];                                } else {                                        dp[i][j] = std::min(dp[i - 1][j - 1], dp[i - 1][j]) +                                                   triangle[i][j];                                }                        }                }                for (int j = 0; j < n; j++) {                        if (dp[n - 1][j] < min) {                                min = dp[n - 1][j];                        }                }                return min;        }};
Loading comments…