From 31e6a1ad95de2a4652796d4367b84655d3653008 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Wed, 25 Jan 2023 20:10:53 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00062.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84.md=20C=E8=AF=AD=E8=A8=80=E6=BB=9A=E5=8A=A8?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15\345\220\214\350\267\257\345\276\204.md" | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git "a/problems/0062.\344\270\215\345\220\214\350\267\257\345\276\204.md" "b/problems/0062.\344\270\215\345\220\214\350\267\257\345\276\204.md" index 2367587c25..4c0e227993 100644 --- "a/problems/0062.\344\270\215\345\220\214\350\267\257\345\276\204.md" +++ "b/problems/0062.\344\270\215\345\220\214\350\267\257\345\276\204.md" @@ -436,6 +436,26 @@ int uniquePaths(int m, int n){ } ``` +滚动数组解法: +```c +int uniquePaths(int m, int n){ + int i, j; + + // 初始化dp数组 + int *dp = (int*)malloc(sizeof(int) * n); + for (i = 0; i < n; ++i) + dp[i] = 1; + + for (j = 1; j < m; ++j) { + for (i = 1; i < n; ++i) { + // dp[i]为二维数组解法中dp[i-1][j]。dp[i-1]为二维数组解法中dp[i][j-1] + dp[i] += dp[i - 1]; + } + } + return dp[n - 1]; +} +``` + ### Scala ```scala From 9d02c76777849bcf287cc3c11805fb8b98db8ce4 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Thu, 26 Jan 2023 17:24:38 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200063.=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E8=B7=AF=E5=BE=84II.md=20C=E8=AF=AD=E8=A8=80=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=A9=BA=E9=97=B4=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\345\220\214\350\267\257\345\276\204II.md" | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git "a/problems/0063.\344\270\215\345\220\214\350\267\257\345\276\204II.md" "b/problems/0063.\344\270\215\345\220\214\350\267\257\345\276\204II.md" index 9aa369563d..b89486e655 100644 --- "a/problems/0063.\344\270\215\345\220\214\350\267\257\345\276\204II.md" +++ "b/problems/0063.\344\270\215\345\220\214\350\267\257\345\276\204II.md" @@ -539,6 +539,39 @@ int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize, int* obst } ``` +空间优化版本: +```c +int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize, int* obstacleGridColSize){ + int m = obstacleGridSize; + int n = obstacleGridColSize[0]; + int *dp = (int*)malloc(sizeof(int) * n); + int i, j; + + // 初始化dp为第一行起始状态。 + for (j = 0; j < n; ++j) { + if (obstacleGrid[0][j] == 1) + dp[j] = 0; + else if (j == 0) + dp[j] = 1; + else + dp[j] = dp[j - 1]; + } + + for (i = 1; i < m; ++i) { + for (j = 0; j < n; ++j) { + if (obstacleGrid[i][j] == 1) + dp[j] = 0; + // 若j为0,dp[j]表示最左边一列,无需改动 + // 此处dp[j],dp[j-1]等同于二维dp中的dp[i-1][j]和dp[i][j-1] + else if (j != 0) + dp[j] += dp[j - 1]; + } + } + + return dp[n - 1]; +} +``` + ### Scala ```scala