Leetcode Unique Paths II
2014-09-20 16:40
309 查看
题目:
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
in the grid.
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.
解题:
类似于Unique Paths,简单DP,状态转移方程:f[i][j] = f[i - 1][j] + f[i][j]
只是注意0,1问题,1的话f[i][j] = 0
代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int row = obstacleGrid.size();
if(!row) return 0;
int col = obstacleGrid[0].size();
vector<vector<int> > f(row, vector<int>(col, 0));
f[0][0] = !obstacleGrid[0][0];
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(obstacleGrid[i][j]) {
f[i][j] = 0;
continue;
}
if(i) f[i][j] += f[i - 1][j];
if(j) f[i][j] += f[i][j - 1];
}
}
return f[row - 1][col - 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
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.
解题:
类似于Unique Paths,简单DP,状态转移方程:f[i][j] = f[i - 1][j] + f[i][j]
只是注意0,1问题,1的话f[i][j] = 0
代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int row = obstacleGrid.size();
if(!row) return 0;
int col = obstacleGrid[0].size();
vector<vector<int> > f(row, vector<int>(col, 0));
f[0][0] = !obstacleGrid[0][0];
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(obstacleGrid[i][j]) {
f[i][j] = 0;
continue;
}
if(i) f[i][j] += f[i - 1][j];
if(j) f[i][j] += f[i][j - 1];
}
}
return f[row - 1][col - 1];
}
};
相关文章推荐
- LeetCode 63: Unique Paths II
- leetcode Unique Paths & Unique Paths II & Minimum Path Sum
- [leetcode] Unique Paths II
- LeetCode--unique-paths-ii
- 【Leetcode】【python】Unique Paths/Unique Paths II
- Unique Paths II -- leetcode
- 《leetCode》:Unique Paths II
- 动态规划小结 - 二维动态规划 - 时间复杂度 O(n*n)的棋盘型,题 [LeetCode] Minimum Path Sum,Unique Paths II,Edit Distance
- [LeetCode][Java] Unique Paths II
- LeetCode刷题【Array】 Unique Paths II
- leetcode Unique Paths II
- LeetCode -- 63 Unique Paths II
- LeetCode-Unique Paths II
- LeetCode 63 --- Unique Paths II
- LeetCode: Unique Paths II
- leetcode Unique Paths II
- LeetCode_Unique Paths II
- Leetcode 动态规划 Unique Paths II
- [Leetcode] Unique Paths II
- LeetCode: Unique Paths I & II & Minimum Path Sum