Update 0063.不同路径II.md

新增TypeScript的一維dp解法
This commit is contained in:
杜羽
2024-06-03 01:23:58 +08:00
committed by GitHub
parent 55e3828135
commit 081e27db22

View File

@ -550,6 +550,27 @@ function uniquePathsWithObstacles(obstacleGrid: number[][]): number {
};
```
// 版本二: dp改為使用一維陣列從終點開始遍歷
```typescript
function uniquePathsWithObstacles2(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