Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
方法一,DFS+备忘录。如果当前位置为obstacle,则返回0,否则进行递归。时间O(n^2),空间O(n^2)。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
const int m = obstacleGrid.size();
const int n = obstacleGrid[0].size();
vector<vector<int> > f(m+1, vector<int>(n+1, -1));
return dfs(obstacleGrid, f, m, n);
}
int dfs(vector<vector<int> > &obstacleGrid, vector<vector<int> > &f, int m, int n)
{
if(m < 1 || n < 1)
return f[m][n] = 0;
if(obstacleGrid[m-1][n-1] == 1)
return f[m][n] = 0;
if(m == 1 && n == 1)
return 1;
if(f[m][n] == -1)
f[m][n] = dfs(obstacleGrid, f, m-1, n) + dfs(obstacleGrid, f, m, n-1);
return f[m][n];
}
};
方法二,DP+滚动数组。时间O(n^2),空间O(n)。注意在第一列中,如果某个位置为
obstacle,则其下面的所有位置均不可达。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int row = obstacleGrid.size();
int col = obstacleGrid[0].size();
vector<int> f(col, 0);
f[0] = (obstacleGrid[0][0]==0);
for(int i=0; i<row; i++)
{
f[0] = f[0] && (obstacleGrid[i][0]==0);
for(int j=1; j<col; j++)
{
if(!obstacleGrid[i][j])
f[j] = f[j-1] + f[j];
else
f[j] = 0;
}
}
return f[col-1];
}
};