题目:
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.
思路:
这题和Unique Paths很像,只不过加了一个路障,我们可以把路障地方的DP设置为0.则可以将Unique Paths的动态规划方法用过来。
时间复杂度:O(m*n)
实现如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& nums) {
int size1 = nums.size();
if (size1 < 1) return 0;
int size2 = nums[0].size();
vector<vector<int>> DP(size1, vector<int>(size2, 1));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
if (nums[i][j] == 1) DP[i][j] = 0; //注意这一步处理
else if (i > 0 && j > 0) DP[i][j] = DP[i][j - 1] + DP[i - 1][j];
else if (i > 0) DP[i][j] = DP[i-1][j];
else if(j>0) DP[i][j] = DP[i][j - 1];
}
return DP[size1 - 1][size2 - 1];
}
};