63. Unique Paths II (2D-dp)
這題跟 leetcode 62 差別主要在不能初始化所有dp 一開始為 1 了, 因為遇到障礙是不能走的
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid != null && obstacleGrid.length == 0) return 0;
int n = obstacleGrid[0].length;
int dp[] = new int[n];
dp[0] = 1; // 預設起始 1
for (int[] row : obstacleGrid) {
for (int j = 0; j < n; j++) {
if (row[j] == 1) { // row's col value, 遇到障礙
dp[j] = 0;
} else if (j > 0) {
dp[j] += dp[j-1];
}
}
}
return dp[n-1];
}
}
easy way to solve
time: O(m*n)
space:(m*n)
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int dp[][] = new int[m][n];
// if has obstacle, the following way will be 0
// 1 1 1 obstacle 0 0 0 0 0
for (int i = 0; i < m ; i++) {
if (obstacleGrid[i][0] == 1) {
break;
}
dp[i][0] = 1;
}
for (int j = 0; j < n ; j++) {
if (obstacleGrid[0][j] == 1) {
break;
}
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 1) { // has obstacle, pass cal this time
continue;
}
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}
/*
top down
if (obstacleGrid[i][j] == 1) {
continue;
}
dp[i][j] = dp[i-1][j] + dp[i][j-1];
*/
Last updated