题目传送地址:​​https://leetcode.cn/problems/unique-paths-ii/​

运行效率:

Leetcode63. 不同路径 II_算法


代码如下:

public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length-1;
int n = obstacleGrid[0].length-1;
return uniquePaths(m, n, obstacleGrid);

}

public static int uniquePaths(int m, int n, int[][] obstacleGrid) {
HashMap<String, Integer> map = new HashMap<>();
return uniqPathsWithMap(m, n, obstacleGrid, map);
}

public static int uniqPathsWithMap(int m, int n, int[][] obstacleGrid, HashMap<String, Integer> map) {
if (obstacleGrid[m][n] == 1) {
return 0;
}
String key = m + ":" + n;
if (map.containsKey(key)) {
return map.get(key);
}
//处理边界情况
if (m == 0) {
while (n>0){
if(obstacleGrid[0][n-1]==1){
return 0;
}
n--;
}
return 1;
}
if(n==0){
while (m>0){
if(obstacleGrid[m-1][0]==1){
return 0;
}
m--;
}
return 1;
}
//要想走到(m,n)位置坐标,有2种可能,第一种是从(m-1,n)到(m,n), 第2种是从(m,n-1)到(m,n)
int i = uniqPathsWithMap(m - 1, n, obstacleGrid, map) + uniqPathsWithMap(m, n - 1, obstacleGrid, map);
map.put(m + ":" + n, i);
return i;
}