diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 6819c19f..daf3d8c5 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -550,6 +550,27 @@ function uniquePathsWithObstacles(obstacleGrid: number[][]): number { }; ``` +// 版本二: dp改為使用一維陣列,從終點開始遍歷 +```typescript +function uniquePathsWithObstacles(obstacleGrid: number[][]): number { + const m = obstacleGrid.length; + const n = obstacleGrid[0].length; + + const dp: number[] = new Array(n).fill(0); + dp[n - 1] = 1; + + // 由下而上,右而左進行遍歷 + for (let i = m - 1; i >= 0; i--) { + for (let j = n - 1; j >= 0; j--) { + if (obstacleGrid[i][j] === 1) dp[j] = 0; + else dp[j] = dp[j] + (dp[j + 1] || 0); + } + } + + return dp[0]; +}; +``` + ### Rust ```Rust