20ms simple C++ standard DP


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

  • 0
    J

    yes, it's the most basic solution, and we can reduce the space complexity further


Log in to reply
 

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