Merge pull request #2571 from xCk27x/master

新增 0063.不同路径II 的TypeScript作法2
This commit is contained in:
程序员Carl
2024-06-26 10:06:23 +08:00
committed by GitHub

View File

@ -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
```Rust ```Rust