原题链接在这里:https://leetcode.com/problems/unique-paths-ii/
是Unique Paths的进阶版题目。思路与Unique Paths相似,不同点在于加了障碍物,DP的更新当前点方式有所不同, 若是此处有障碍物,res里这一点就是0,若此处没有障碍物,res里这一点就同行上一列和同列上一行的和。
Note: 初始化是点res[0][0].
AC Java:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0){
return 0;
}
int h = obstacleGrid.length;
int w = obstacleGrid[0].length;
int[][] res = new int[h][w];
res[0][0] = obstacleGrid[0][0] == 1 ? 0:1; //error
for(int i = 1; i < h; i++){
res[i][0] = obstacleGrid[i][0] == 1 ? 0:res[i-1][0];
}
for(int i = 1; i < w; i++){
res[0][i] = obstacleGrid[0][i] == 1 ? 0:res[0][i-1];
}
for(int i = 1; i < h; i++){
for(int j = 1; j < w; j++){
res[i][j] = obstacleGrid[i][j] == 1 ? 0:res[i-1][j] + res[i][j-1];
}
}
return res[h-1][w-1];
}
}
对应的本题也有像Unique Paths一般的降维存储历史信息的方法。
Note: 更新时这里j是从0开始与Unique Paths不同,还有用res[j-1]前要确保j>0.
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
//Method 2
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length ==0){
return 0;
}
int h = obstacleGrid.length;
int w = obstacleGrid[0].length;
int [] res = new int[w];
res[0] = obstacleGrid[0][0] == 1 ? 0 : 1;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){ //error
if(obstacleGrid[i][j] == 1){
res[j] = 0;
}else{
if(j>0){ //error
res[j] += res[j-1];
}
}
}
}
return res[w-1];
}
}