mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0063.不同路径II.md C语言优化空间版本
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user