Leek-- 931. The minimum sum of the descending path

Topic link: 931. Minimum sum of descending paths - LeetCode 

The following is the process of solving this problem with the idea of ​​​​dynamic programming. I believe that everyone can understand and master this classic dynamic programming problem.

Reference Code:

class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n=matrix.size();
        //多开一行,多开两列,先把所有都初始化成最大值
        vector<vector<int>> dp(n+1,vector<int>(n+2,INT_MAX));
        //把第一行初始化为0
        for(int i=0;i<=n+1;i++)
        {
            dp[0][i]=0;
        }
        //填表
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                dp[i][j]=min(min(dp[i-1][j-1],dp[i-1][j]),dp[i-1][j+1])+matrix[i-1][j-1];
            }
        }
        //找最后一行的最小值
        int min=dp[n][0];
        for(int i=1;i<=n+1;i++)
        {
            if(dp[n][i]<min)
            {
                min=dp[n][i];
            }
        }
        return min;
    }
};

 The above is the whole process of analyzing this dp question, have you learned it yet? If the above solutions are helpful to you, then please be careful and pay attention to it. We will continue to update the classic questions of dynamic programming in the future. See you in the next issue! ! ! ! ! ! ! ! !

Guess you like

Origin blog.csdn.net/weixin_70056514/article/details/131502572