Skip to content

Commit

Permalink
添加 0063.不同路径II.md C语言优化空间版本
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Jan 26, 2023
1 parent 31e6a1a commit 9d02c76
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions problems/0063.不同路径II.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9d02c76

Please sign in to comment.