原文链接:Unique Paths II
【思路】
与 leetcode 62. Unique Paths-唯一路径|动态规划不同的是
这里给机器人增加了障碍物,需要在递推式res[i][j]=res[i-1][j]+res[i][j-1]之前增加一个判断,如果则res[i][j]=0,则res[i][j] = 0:
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int[][] pathCount = new int[obstacleGrid.length][obstacleGrid[0].length];
for (int i = 0; i < obstacleGrid.length && obstacleGrid[i][0] != 1; i++)
pathCount[i][0] = 1;
for (int j = 0; j < obstacleGrid[0].length && obstacleGrid[0][j] != 1; j++)
pathCount[0][j] = 1;
for (int i = 1; i < obstacleGrid.length; i++)
for (int j = 1; j < obstacleGrid[0].length; j++)
if (obstacleGrid[i][j] == 1) pathCount[i][j] = 0;
else pathCount[i][j] = pathCount[i - 1][j] + pathCount[i][j - 1];
return pathCount[obstacleGrid.length - 1][obstacleGrid[0].length - 1];
}
43 / 43
test cases passed. Runtime: 1 ms Your runtime beats 17.74% of javasubmissions.
【优化】
这里同样可以将二维数组优化为一维数组。pathCount[i]存放的是矩阵m × n矩阵,m行i列的走法数:
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int[] pathCount = new int[obstacleGrid[0].length];
pathCount[0] = 1;
for (int i = 0; i < obstacleGrid.length; i++)
for (int j = 0; j < obstacleGrid[0].length; j++)
if (obstacleGrid[i][j] == 1) pathCount[j] = 0;
else if (j > 0) pathCount[j] += pathCount[j - 1];
return pathCount[obstacleGrid[0].length - 1];
}
43 / 43 test cases passed. Runtime: 1 ms Your runtime beats 17.74% of javasubmissions.