1. 题目
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 3×3 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.
2. 思路
第一遍用递归的方式来计算,当矩阵太大了递归太多超时了。
第二遍改为迭代方案,从右下往左上走,保留每个点[i,j]走到底的路径数量,就可以通过加和得到下一步的大小。复杂度O(m*n)。
3. 代码
耗时:6ms
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
//return upwo(obstacleGrid, 0, 0);
return upwo(obstacleGrid);
}
// 迭代的方案
// 多加一行一列, 填为0,方便迭代计算. 为了简化最右下的点,将右下的右边点设置为1
int upwo(vector<vector<int>>& og) {
int row = og.size();
if (row == 0) { return 0; }
int col = og[0].size();
if (col == 0) { return 0; }
if (og[0][0] == 1 || og[row-1][col-1] == 1) { return 0; }
int way[row+1][col+1];
for (int i = 0; i < row + 1; i++) {
way[i][col] = 0;
}
for (int j = 0; j < col + 1; j++) {
way[row][j] = 0;
}
way[row-1][col] = 1;
for (int i = row-1; i >= 0; i--) {
for (int j = col-1; j >= 0; j--) {
if (og[i][j] == 1) {
way[i][j] = 0;
} else {
way[i][j] = way[i+1][j] + way[i][j+1];
}
}
}
return way[0][0];
}
// 超时的方案
// 用递归的方式来计算
// 每次可以向右和相下两种方向,如果某个方向是1,则此方向的种类是0
int upwo(vector<vector<int>>& og, int i, int j) {
if (og[i][j] == 1) { return 0; }
int row = og.size();
if (row == 0) { return 0; }
int col = og[0].size();
if (col == 0) { return 0; }
if (i == row - 1 && j == col - 1) { return 1; }
if (i == row - 1) { return upwo(og, i, j + 1); }
if (j == col - 1) { return upwo(og, i + 1, j); }
return upwo(og, i, j + 1) + upwo(og, i + 1, j);
}
};