[LeetCode]20. Unique Paths II唯一路径
2015-10-09 21:32
676 查看
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.
解法:还是使用动态规划。不同的是若遇到障碍,则说明到此位置后面就行不通了,路径数目为0。注意初始化不能再是path[i][0]=1,path[0][j]=1(0<=i<m,0<=j<n),而是path[0][0]=1,因为第一行和第一列上就有可能有障碍。
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.
解法:还是使用动态规划。不同的是若遇到障碍,则说明到此位置后面就行不通了,路径数目为0。注意初始化不能再是path[i][0]=1,path[0][j]=1(0<=i<m,0<=j<n),而是path[0][0]=1,因为第一行和第一列上就有可能有障碍。
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int res = 0; if(obstacleGrid.empty() || obstacleGrid[0].empty()) return res; int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<int> path(n, 0); path[0] = 1; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(obstacleGrid[i][j] == 1) path[j] = 0; else if(j > 0) path[j] += path[j - 1]; } } res = path[n - 1]; return res; } };
相关文章推荐
- 【Foundation-86-3】#import <Foundation/NSValue.h> 初始化
- UINavigationController+storyboard
- General Problem Solving Techniques [Intermediate-1]~F - Tian Ji -- The Horse Racing
- 1670: [Usaco2006 Oct]Building the Moat护城河的挖掘
- iOS:UIResponser控件的介绍(响应者)
- BestCoder 1st Anniversary ($) HDU5312 Sequence
- builder模式
- SPOJ Query on a tree (树链剖分 + 线段树)
- 浅谈UIScrollView的用法
- 【Foundation-86-2】#import <Foundation/NSValue.h>
- UESTC 86 Divide(贪心+二进制)
- 几种键盘回收方式
- General Problem Solving Techniques [Intermediate-1]~E - The Trip, 2007
- POJ 3017 Cut the Sequence (单调队列优化DP)
- UINavigationController
- UESTC 84 Binary Operations(位运算+DP)
- [LeetCode]19. Unique Paths唯一路径
- TestDataBuilder自动生成工具
- UE4高级功能-初探超大无缝map的实现LevelStream
- UE4次世代的移动平台渲染技术