https://leetcode.com/problems/unique-paths-ii/
跟Unique Path基本一样,只需要加一个判断条件,当当前格是障碍时,到当前格的路径数为0,就可以了,先用的二维数组DP:
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] paths = new int[m][n];
paths[0][0]=1;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(obstacleGrid[i][j]==1){
paths[i][j]=0;
continue;
}
if(i==0 && j==0) continue;
else if(i==0) paths[i][j] = paths[i][j-1];
else if(j==0) paths[i][j] = paths[i-1][j];
else paths[i][j] = paths[i][j-1] + paths[i-1][j];
}
}
return paths[m-1][n-1];
}
可优化为一维数组DP,但这时候注意,在填每行的值时,每行第一个值必须检查一下是否是障碍,如果是,则改为0,不是则保持跟上一行第一个值一致:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[] paths = new int[n];
paths[0] = 1;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(obstacleGrid[i][j]==1){
paths[j]=0;
continue;
}
if(j==0) continue;
paths[j] = paths[j]+paths[j-1];
}
}
return paths[n-1];
}
}
时间复杂度O(m*n), 空间复杂度O(n)
总结:在题目变形时,要考虑全面,尽量写代码前就想好,不要写完调试后再改