[LeetCode] Unique Paths II
2015-03-07 13:45
344 查看
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
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is
Note: m and n will be at most 100.
Hide Tags
Array Dynamic Programming
思路:在Unique Paths的基础上,加上obstacleGrid[i-1][j-1]==0 时,f[i][j]=0,另外,注意红色部分的特殊处理。
思路二:上门的思路改成滚动数组
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
1and
0respectively 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.
Hide Tags
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] ; } };
思路二:上门的思路改成滚动数组
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 ; } };
相关文章推荐
- [Leetcode]Unique Paths II
- LeetCode题解:Unique Paths II
- Unique Paths II - LeetCode 63
- 28_leetcode_Unique Paths II
- [LeetCode]Unique Paths II
- [Leetcode] Unique Paths II
- leetcode 【 Unique Paths II 】 python 实现
- [LeetCode] Unique Paths II
- LeetCode Unique Paths II
- leetcode ---Unique Paths II
- leetcode || 63、Unique Paths II
- [leetcode刷题系列]Unique Paths II
- leetcode: Unique Paths II
- 开始刷leetcode day60: Unique Paths II
- leetcode unique paths ii
- [LeetCode] Unique Paths II
- LeetCode 62 Unique Paths II
- Leetcode-Unique Paths II
- 【LeetCode】Unique Paths II
- Leetcode Unique Paths II