Share my C++ DP clear code


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.