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)
Last updated
Was this helpful?