63. Unique Paths II

DP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;

// 定义 dp[i][j] 为从起点到达 obstacleGrid[i][j] 的路径数
int[][] dp = new int[m][n];
dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j] == 0) {
if (i > 0) {
dp[i][j] += dp[i - 1][j];
}
if (j > 0) {
dp[i][j] += dp[i][j - 1];
}
}
}
}

return dp[m - 1][n - 1];
}
}

DP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;

int[] dp = new int[n];
dp[0] = obstacleGrid[0][0] == 1 ? 0 : 1;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j] == 0) {
if (j > 0) {
dp[j] += dp[j - 1];
}
} else {
dp[j] = 0;
}
}
}

return dp[n - 1];
}
}

降维后注意在特定情况下需要将数组中的元素置为 0。

References

63. Unique Paths II