Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1878 from KingArthur0205/master
Browse files Browse the repository at this point in the history
添加0062.不同路径.md C语言滚动数组解法, 0063.不同路径II.md C语言优化空间版本
  • Loading branch information
youngyangyang04 authored Jan 31, 2023
2 parents 025c7f2 + b7c8ba8 commit 316e470
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
20 changes: 20 additions & 0 deletions problems/0062.不同路径.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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 316e470

Please sign in to comment.