【Leetcode】【Medium】Unique Paths II
2015-04-30 00:45
435 查看
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
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 I 的思路,对于Unique Paths II 我们依然希望使用o(n)的额外空间和o(m+n)的时间复杂度;
Unique Paths II中grid[i][n-1]和grid[i-1][n-1]不再总是相等,即格子中最右侧一列每一格存在的路径条数可能为1或0;
因此,为了继续使用Unique Paths I中数组迭代的技巧,需要每次迭代前计算新一轮的grid[i][n-1]值,这样才能继续计算grid[i][0]~grid[i][n-2]的值,从而完成此次迭代;
如果原始格子内为1,则对应此位值置0,表示从此位置不存在到终点的有效路径。
代码:
注:
养成好习惯,除非特殊说明,不要在原始入参上修改,尤其是入参是地址形式。
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 I 的思路,对于Unique Paths II 我们依然希望使用o(n)的额外空间和o(m+n)的时间复杂度;
Unique Paths II中grid[i][n-1]和grid[i-1][n-1]不再总是相等,即格子中最右侧一列每一格存在的路径条数可能为1或0;
因此,为了继续使用Unique Paths I中数组迭代的技巧,需要每次迭代前计算新一轮的grid[i][n-1]值,这样才能继续计算grid[i][0]~grid[i][n-2]的值,从而完成此次迭代;
如果原始格子内为1,则对应此位值置0,表示从此位置不存在到终点的有效路径。
代码:
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<int> col (n, 0); col[n-1] = obstacleGrid[m-1][n-1] == 1 ? 0 : 1; for (int i = m - 1; i >= 0; --i) { col[n-1] = obstacleGrid[i][n-1] == 1 ? 0 : col[n-1]; for (int j = n - 2; j >= 0; --j) { col[j] = obstacleGrid[i][j] == 1 ? 0 : col[j] + col[j+1]; } } return col[0]; } };
注:
养成好习惯,除非特殊说明,不要在原始入参上修改,尤其是入参是地址形式。
相关文章推荐
- [Leetcode 63, Medium] Unique Paths II
- 【LeetCode】(63)Unique Paths II(Medium)
- LeetCode-63-Unique Paths II(动规)-Medium
- leetcode 063 —— 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 II
- 【Leetcode】【python】Unique Paths/Unique Paths II
- [LeetCode]Unique Paths II
- LeetCode Unique Paths II
- leetcode——63—— Unique Paths II
- 【LeetCode】(63)Unique Paths (Medium)
- [LeetCode] Unique Paths II
- LeetCode -- Unique Paths II
- LeetCode - Unique Paths II
- LeetCode 95. Unique Paths II
- 【LeetCode】Unique Paths I && II