From 081e27db222d0b3775b84bed6e3629d5de8b96b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E7=BE=BD?= <90547641+xCk27x@users.noreply.github.com> Date: Mon, 3 Jun 2024 01:23:58 +0800 Subject: [PATCH] =?UTF-8?q?Update=200063.=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增TypeScript的一維dp解法 --- problems/0063.不同路径II.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 6819c19f..78507a84 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -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