Created
August 11, 2013 00:12
-
-
Save qqibrow/6202761 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First solution. This cannot pass larget test. | |
class Solution { | |
public: | |
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { | |
if(!obstacleGrid.size() || !obstacleGrid[0].size() || obstacleGrid[0][0]) | |
return 0; | |
else | |
return getUniquePath(obstacleGrid.size()-1, obstacleGrid[0].size()-1, obstacleGrid); | |
} | |
private: | |
int getUniquePath(int i, int j, const vector<vector<int>> &obstacleGrid) { | |
assert( i >= 0 && j >= 0); | |
if (obstacleGrid[i][j]) | |
return 0; | |
else if ( !i && !j) | |
return 1; | |
else if(!i) | |
return getUniquePath(i, j-1, obstacleGrid); | |
else if(!j) | |
return getUniquePath(i-1, j, obstacleGrid); | |
else | |
return getUniquePath(i-1, j, obstacleGrid) + getUniquePath(i, j-1, obstacleGrid); | |
} | |
}; | |
// Second solution. Passed the large test. | |
class Solution { | |
public: | |
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { | |
if(!obstacleGrid.size() || !obstacleGrid[0].size() || obstacleGrid[0][0]) | |
return 0; | |
const int height = obstacleGrid.size(); | |
const int width = obstacleGrid[0].size(); | |
int path[height][width]; | |
for( int i = 0; i < height; ++i) | |
for( int j = 0; j < width; ++j) { | |
if (obstacleGrid[i][j]) | |
path[i][j] = 0; | |
else if ( !i && !j) | |
path[i][j] = 1; | |
else if(!i) | |
path[i][j] = path[i][j-1]; | |
else if(!j) | |
path[i][j] = path[i-1][j]; | |
else | |
path[i][j] = path[i-1][j] + path[i][j-1]; | |
} | |
return path[height - 1][width - 1]; | |
} | |
}; | |
// Third solution. Optimization space complaxity(Not finished). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment