unique paths II
2015-02-01 15:08
183 查看
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.
网上看到别人写的,1D DP很巧妙, 因为总是往一个方向走,实际上只需要维护一个1D的数组就可以了。 和上面不一样的是需要有一个检查是不是有obstacle,如果有那么设置为0,此路不通,在tbl[j+1]中则认为此为无效。 而在其他的循环中, tb[i][j]则由其他来维护,也就不需要担心=0会抹掉什么。 挺绕的。。。
回到2D的规划,因为条件变了,中间有阻隔,上次取巧的设置为1改起来好麻烦,设置0,0为1,然后按照1维来更新通不通, 这个在我看来的好处是处理2x2的数组有用,再就是本来你也少不了需要判断m=1,n=1的时候。 从YU'S coding garden那里直接抄来吧。。。
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.
网上看到别人写的,1D DP很巧妙, 因为总是往一个方向走,实际上只需要维护一个1D的数组就可以了。 和上面不一样的是需要有一个检查是不是有obstacle,如果有那么设置为0,此路不通,在tbl[j+1]中则认为此为无效。 而在其他的循环中, tb[i][j]则由其他来维护,也就不需要担心=0会抹掉什么。 挺绕的。。。
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> tbl(n,0); tbl[0]=1; for (int i=0; i<m; i++){ for (int j=0; j<n; j++){ if (obstacleGrid[i][j]==1) tbl[j]=0; else tbl[j]+=tbl[j-1]; } } return tbl[n-1]; } };
回到2D的规划,因为条件变了,中间有阻隔,上次取巧的设置为1改起来好麻烦,设置0,0为1,然后按照1维来更新通不通, 这个在我看来的好处是处理2x2的数组有用,再就是本来你也少不了需要判断m=1,n=1的时候。 从YU'S coding garden那里直接抄来吧。。。
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<int> > arr(m,vector<int>(n,0)); if (obstacleGrid[0][0]==1){return 0;} arr[0][0]=1; for (int i=1;i<m;i++){ if (obstacleGrid[i][0]!=1){ arr[i][0] = arr[i-1][0]; } } for (int i=1;i<n;i++){ if (obstacleGrid[0][i]!=1){ arr[0][i] = arr[0][i-1]; } } for (int i=1;i<m;i++){ for(int j=1;j<n;j++){ if (obstacleGrid[i][j]!=1){ arr[i][j] = arr[i][j-1] + arr[i-1][j]; } } } return arr[m-1][n-1]; } };
相关文章推荐
- Unique Paths II [LeetCode]
- LeetCode--No.63--Unique Paths II
- [LeetCode]Unique Paths II, 解题报告
- LeetCode(63)Unique Paths II
- [Leetcode] Unique Paths II
- Unique Paths II
- Leetcode | Unique Paths I & II
- leetCode+Unique Paths II
- 【LeetCode】Unique Paths I && II && Minimum Path Sum
- [LeetCode] Unique Paths II
- leetcode63 Unique Paths II
- 63 Unique Paths II
- Unique_Paths_II
- FTPrep, 63 Unique Paths II
- LeetCode--Unique Paths II
- leetcode---Unique Paths II---dp
- Unique Paths II
- Unique Paths II
- Unique Paths II
- Unique Paths II