2022-4-19 Leetcode 64. Minimum Path Sum - [Simple Dynamic Programming]


insert image description here
insert image description here
Two-dimensional dp written by myself

class Solution {
    
    
public:
    int minPathSum(vector<vector<int>>& grid) {
    
    
        if(grid.empty())
        return 0;
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> dp(m,vector<int>(n));
        dp[0][0] = grid[0][0];
        for(int j = 1;j < n;j++){
    
    
            dp[0][j] = grid[0][j] + dp[0][j-1];
        }

        for(int i = 1;i < m;i++){
    
    
            dp[i][0] = grid[i][0] + dp[i-1][0];
        }
        
        for(int i = 1;i < m;i++){
    
    
            for(int j = 1;j < n;j++){
    
    
                dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }
};

compressed space

class Solution {
    
    
public:
    int minPathSum(vector<vector<int>>& grid) {
    
    
        if(grid.empty())
        return 0;
        int m = grid.size();
        int n = grid[0].size();
        vector<int> dp(n);
        
        for(int i = 0;i < m;i++){
    
    
            for(int j = 0;j < n;j++){
    
    
                if(i == 0 && j == 0){
    
    
                    dp[0] = grid[0][0];
                    //不加这个会溢出的
                }else if(i == 0 && j > 0){
    
    
                    dp[j] = dp[j-1] + grid[i][j];
                }else if(j == 0 && i > 0){
    
    
                    dp[j] = dp[j] + grid[i][j];
                }else{
    
    
                    dp[j]  = min(dp[j],dp[j-1]) + grid[i][j];
                }
            }
        }
        return dp[n-1];
        }
        }

The key to compressing the space is that currently in row i and column j, the number on column j-1 goes right to the j-th position, and the j-th position goes from the top to the j-th position.
If you want to understand, you can compress.

Guess you like

Origin blog.csdn.net/weixin_51187533/article/details/124265071