C++ 9ms DP solution with O(n) space


  • 0
    M
    class Solution {
    public:
        int minPathSum(vector<vector<int>>& grid) {
            int row = grid.size();
            if(row == 0) return 0;
            int col = grid[0].size();
            
            vector<int> pre(col+1, INT_MAX);
            pre[1] = 0;
            for(int i = 0; i < row; ++i){
                for(int j = 0; j < col; ++j){
                    pre[j+1] = min(pre[j], pre[j+1]) + grid[i][j];
                }
            }
            return pre[col];
        }
    };
    

Log in to reply
 

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