LeetCode -- Unique Paths II
2016-02-25 12:50
267 查看
Question:
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.
Analysis:
根据“Unique Paths”题目:
现在想象假设在grid中存在一些障碍,那么应该会有几条不同的路径呢?
1表示此处是障碍,不能走;0表示此处可以行走。
思路:根据前面两个题目的经验,仍然使用动态规划,额外申请一块空间,当此处在原网格中是1,表示此处走不通,,所以前面累计的路径个数清零。注意一些特殊情况,如start位置或finish位置为1则一定没有路径。
Answer:
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
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.
Analysis:
根据“Unique Paths”题目:
现在想象假设在grid中存在一些障碍,那么应该会有几条不同的路径呢?
1表示此处是障碍,不能走;0表示此处可以行走。
思路:根据前面两个题目的经验,仍然使用动态规划,额外申请一块空间,当此处在原网格中是1,表示此处走不通,,所以前面累计的路径个数清零。注意一些特殊情况,如start位置或finish位置为1则一定没有路径。
Answer:
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0][0] == 1 || obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1] == 1) return 0; if(obstacleGrid.length == 1 || obstacleGrid[0].length == 1) return 1; int m = obstacleGrid.length, n = obstacleGrid[0].length; int[][] dp = new int[m] ; dp[0][0] = 1; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(i == 0 && j == 0) continue; else if(i == 0 && j != 0) { if(obstacleGrid[i][j] ==1) dp[i][j] = 0; else dp[i][j] = dp[i][j-1]; } else if(i != 0 && j == 0) { if(obstacleGrid[i][j] ==1) dp[i][j] = 0; else dp[i][j] = dp[i-1][j]; } else { if(obstacleGrid[i][j] ==1) dp[i][j] = 0; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } } return dp[m-1][n-1]; } }
相关文章推荐
- LeetCode -- Unique Paths
- Cordova使用build命令出错: Could not create the Java Virtual Machine.
- 通过UIGraphics重新设置image的大小
- Your build settings specify a provisioning profile with the UUID, no provisioning profile was
- 6.UITabBarController
- 欢迎使用CSDN-markdown编辑器
- Android Studio 模拟器无法启动问题(x86 emulation currently requires hardware acceleration。。。)
- iOS 9 学习系列: UIStack View
- Build.VERSION_CODES.HONEYCOMB
- 在C 函数中保存状态:registry、reference和upvalues
- Build.VERSION.SDK_INT
- iOS之XCode在Interface Builder通过16进制选择选择颜色
- UILabel属性集合
- iOS 9开发小技巧:LayoutGuide,Storyboard Reference
- iOS个人整理17-警示框--UIAlertController
- 百度UEditor编辑器setContent innerHtml 未定义报错。
- String,StringBuffer与StringBuilder的区别??
- UIView的一些常用属性和方法
- iOS UITableView中关于cell里的按钮被点击时如何确定是哪一个section
- 正确使用SQL Server 2012中的SEQUENCE