【LeetCode】63. Unique Paths II
来源:互联网 发布:java从大到小排序方法 编辑:程序博客网 时间:2024/05/22 00:20
题目描述
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.
解题思路
动态规划。
思路与【LeetCode】62. Unique Paths 基本相同。
只是此处需要加多一个对于障碍物obstacle的判断,如果所在的地方是障碍物,那么应该将它的状态设置为0,因为没有任何路线可以到达它。
注意开始处和结束处不可以是障碍物。
AC代码
class Solution {public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int ans = 0; int m = obstacleGrid.size(); if (m == 0) return ans; int n = obstacleGrid[0].size(); if (n == 0) return ans; if (obstacleGrid[0][0] || obstacleGrid[m - 1][n - 1]) return ans; vector<vector<int>> dp; for (int i = 0; i <= m; ++i) { vector<int> temp(n + 1, 0); dp.push_back(temp); } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (i == 1 && j == 1) dp[i][j] = 1; else if (obstacleGrid[i - 1][j - 1]) dp[i][j] = 0; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j]; } } return dp[m][n]; }};
0 0
- LeetCode --- 63. Unique Paths II
- LeetCode 63.Unique Paths II
- [leetcode] 63.Unique Paths II
- [leetcode] 63.Unique Paths II
- Leetcode 63. Unique Paths II
- LeetCode 63. Unique Paths II
- [leetcode] 63. Unique Paths II
- leetcode 63. Unique Paths II
- 63. Unique Paths II LeetCode
- LeetCode 63. Unique Paths II
- [LeetCode]63. Unique Paths II
- leetcode 63. Unique Paths II
- LeetCode *** 63. Unique Paths II
- leetcode 63. Unique Paths II
- Leetcode:63. Unique Paths II
- LeetCode 63. Unique Paths II
- leetcode 63.Unique Paths II
- LeetCode 63. Unique Paths II
- Alamofire源码解读系列(四)之参数编码(ParameterEncoding)
- AOE网
- JMS学习七(ActiveMQ消息持久化)
- 存储器(内存)管理之分区式分配
- Spark学习-RDD编程基础
- 【LeetCode】63. Unique Paths II
- K好数
- Remote view API
- Vue-ant
- Hive正则表达式对数据过滤
- RESTful API设计系列四:URLs
- 输入输出
- 快速创建一个servlet并且在web.xml配置和使用它
- Ubuntu上安装Arduino IDE