63. **Unique Paths II
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
63. **Unique Paths II
https://leetcode.com/problems/unique-paths-ii/description/
题目描述
Follow up for
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]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
Note: m
and n
will be at most 100.
解题思路
在上一题的基础上, 如果某些空格是不能走的, 存在障碍物, 那么到达 grid 的右下角有多少种走法?
思路: 注意两点:
- 初始化的的时候, 如果
obstacleGrid = {0, 1, 0, 0}
, 那么dp
的结果就是{1, 0, 0, 0}
, 而不是{1, 0, 1, 1}
, 因为有障碍物, 所有障碍物的位置以及它后面的位置都不能走, 但注意, 是初始化的时候; - 仅在
obstacleGrid[i][j] != 1
时,d[i][j] = d[i - 1][j] + d[i][j - 1]
成立.
C++ 实现 1
注意 dp
被设置为 vector<vector<long long>>
, 是因为如果设置为 vector<vector<int>>
, 那有个测试用例会导致报错:
Line 44: Char 45: runtime error: signed integer overflow: 1053165744 + 1579748616 cannot be represented in type 'int' (solution.cpp)
设置为 long long
可以避免. 但两年前的提交代码中使用的就是 vector<vector<int>>
能通过 100% 的测试用例. 时代变了啊.
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
// 一开始就是障碍物, 那么就不用走了.
if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0]) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<long long>> dp(m, vector<long long>(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i)
dp[i][0] = 1;
for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j)
dp[0][j] = 1;
for (int i=1; i<m; i++) {
for (int j=1; j<n; j++) {
if (!obstacleGrid[i][j])
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
C++ 实现 2
具体思路可以参考 62. Unique Paths** 代码来自: 4ms O(n) DP Solution in C++ with Explanations
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int m = obstacleGrid.size() , n = obstacleGrid[0].size();
vector<vector<long long>> dp(m+1,vector<long long>(n+1,0));
dp[0][1] = 1;
for(int i = 1 ; i <= m ; ++i)
for(int j = 1 ; j <= n ; ++j)
if(!obstacleGrid[i-1][j-1])
dp[i][j] = dp[i-1][j]+dp[i][j-1];
return dp[m][n];
}
};