leetcode ---Unique Paths II
2016-02-25 01:27
417 查看
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
大概意思:和Unique Paths差不多,但是,在网格中会有些障碍,用1来表示;
方法一:和Unique Paths方法一类似,探究到达全部点的路径数(n=上+右),但是这里,将障碍那点的路径数为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.
大概意思:和Unique Paths差不多,但是,在网格中会有些障碍,用1来表示;
方法一:和Unique Paths方法一类似,探究到达全部点的路径数(n=上+右),但是这里,将障碍那点的路径数为0;
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; int n = obstacleGrid[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(obstacleGrid[i][j] == 1) { obstacleGrid[i][j] = 0; //这里将障碍设置成0,代表到达该点的路径是0条; } else { if(i == 0 && j == 0) obstacleGrid[i][j] = 1; else if(i == 0 && j > 0) obstacleGrid[i][j] = obstacleGrid[i][j-1]; else if(i > 0 && j == 0) obstacleGrid[i][j] = obstacleGrid[i-1][j]; //关键是先找到,最上和最右边的点的路径条数;逐渐递推到右下角 else obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]; } } } return obstacleGrid[m-1][n-1]; } } 方法二:回溯法 public class UnquePaths { static int[] DX ={0,1}; static int[] DY ={1,0}; static int a ; public static int uniquePathsWithObstacles(int[][] obstacleGrid) { return Vertify(obstacleGrid,0,0); //编程时,先把需要的函数写好,然后添加需要的参数(具体看要怎么用,不要的参数,删掉),这里的参数往往是初始值 //考虑好返回什么 } public static int Vertify(int[][] board,int x,int y){ if(x==board.length-1&&y==board[0].length-1) a++; //当要设置计数器来记录有多少满足的条件的解时,不能在函数内设置计数;当函数回溯递归的时候,计数器会跟着变化(清零) //应该在类中,定义类属性,而不受递归的干扰! for(int i=0;i!=2;i++){ int xx = x+DX[i]; int yy = y+DY[i]; if(xx>=board.length||yy>=board[0].length||yy<0||xx<0) continue; //当不满足条件的时候,可以使用continue,跳过这一循环; if(board[xx][yy]==1) continue; Vertify(board,xx,yy); //考虑好,怎么进行下一步 } return a; } 回溯总结:做题时多debug,就能发现问题所在;本题出现在计数方式有问题; 很遗憾,虽然是自己写的,但是出现超时。 方法三:DP 动态规划: 待更!~
相关文章推荐
- HDU 3726 Graph and Queries
- Quick Sort
- [Locked] Binary Tree Longest Consecutive Sequence
- Arduino、arm、树莓派、单片机四者有什么不同?
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- 浅谈 easyui tabs 的href和content属性
- QSqlQuery::value: not positioned on a valid record
- Java break continue return 的区别
- easyUI 对话框的关闭事件
- UITableView 小节-备
- GitLab: Failed to authorize your Git request: inte
- [leetcode] Divide and Conquer
- iOS UITableView的使用大全-备用
- 设计模式:Builder模式(多个构造器参数时可显著改善可读性)
- dialog子线程操作UI异常:Only the original thread that created a view hierarchy can touch its views
- dialog子线程操作UI异常:Only the original thread that created a view hierarchy can touch its views
- WeUI 入门教程
- 传智播客168期JavaEE就业班(第十天 request response)
- ORA-02287:此处不允许序号(sequence number not allowed here) 的避免以及强制实现
- UIAutomator定位Android控件的方法实践和建议