[LeetCode] Unique Paths II
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.
Array Dynamic Programming
思路:在Unique Paths的基础上,加上obstacleGrid[i-1][j-1]==0 时,f[i][j]=0,另外,注意红色部分的特殊处理。
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<int> row(n + 1, 0); vector<vector<int> > f(m + 1, row); if(obstacleGrid[0][0] == 1) return 0; f[1][1] = 1; for(int i = 1; i <= m; i ++) { for(int j = 1; j <= n; j ++) { if(i == 1 && j == 1) continue; if(obstacleGrid[i-1][j-1] == 1) f[i][j] = 0; else f[i][j] = f[i-1][j] + f[i][j-1]; } } return f[m][n]; } };
思路二:上门的思路改成滚动数组
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); if(obstacleGrid[0][0] == 1) return 0; vector<int> f(n + 1, 0); f[1] = 1; for(int i = 1; i <= m; i ++) { for(int j = 1; j <= n; j ++) { if(i == 1 && j == 1) continue; if(obstacleGrid[i-1][j-1] == 1) f[j] = 0; else f[j] = f[j] + f[j-1]; } } return f[n]; } };