63. Unique Paths II
来源:互联网 发布:linux教程pdf 编辑:程序博客网 时间:2024/05/17 07:43
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 Path的动态规划思路,但是还要考虑左边界和上边界的特殊情况。为了解决边界的问题,我们可以在方格的左边和上边各加一个“边框”,即声明整数数组paths[m+1][n+1]而不是paths[m][n]。其中paths[0][1]初始化为1,其余格子初始化为0。这样从左到右,从上到下计算,可以巧妙地解决边界的特殊情况。
class Solution {public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(), n = obstacleGrid[0].size(); int paths[m+1][n+1]; for (int i = 0; i < m + 1; i++) for (int j = 0; j < n + 1; j++) { paths[i][j] = 0; } paths[0][1] = 1; for (int i = 1; i < m + 1; i++) { for (int j = 1; j < n + 1; j++) { if (obstacleGrid[i-1][j-1] == 0) { paths[i][j] = paths[i-1][j] + paths[i][j-1]; } } } return paths[m][n]; }};
阅读全文
0 0
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 63. Unique Paths II
- 逆向分析涉及的工具及OD快捷键
- 【51nod】-1305 Pairwise Sum and Divide(数学)
- 赚钱
- 机器学习数学基础001-矩阵及矩阵的基本表示
- JAVA | 47
- 63. Unique Paths II
- Canvas 入门1 描边、渐变、图像、阴影、填充
- vi常用键位
- 如何使用RedisTemplate访问Redis数据结构
- Robot Framework 源代码阅读笔记 之五
- angular的hero例子(3)
- python远程批量执行
- 数组栈的操作
- Oracle 常用语句列表