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