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.
大概意思:和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 动态规划: 待更!~