C++ solution with O(1) space complexity and O(mn) time complexity


  • 0
    E
    class Solution {
    public:
        int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
            vector<vector<int>> & grid = obstacleGrid;
            if(grid.empty()) return 0;
            int row = grid.size();
            int col = grid[0].size();
            for(int i = 0; i < row; i++){
                for(int j = 0; j < col; j++){
                    if(i==0 && j==0) grid[i][j] = (grid[i][j]==1 ? 0 : 1);
                    else if(i==0) grid[i][j] = (grid[i][j] == 1 ? 0 : grid[i][j-1]);
                    else if(j==0) grid[i][j] = (grid[i][j] == 1 ? 0 : grid[i-1][j]);
                    else grid[i][j] = (grid[i][j] == 1 ? 0 : grid[i-1][j] + grid[i][j-1]);
                }
            }
            return grid[row-1][col-1];
        }
    };
    

Log in to reply
 

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