Merge pull request #1651 from pzppzz/master

feat:添加0063不同路径内存优化javascript版本
This commit is contained in:
程序员Carl 2022-09-25 10:26:09 +08:00 committed by GitHub
commit f7d5b71c03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 0 deletions

View File

@ -382,8 +382,37 @@ var uniquePathsWithObstacles = function(obstacleGrid) {
return dp[m - 1][n - 1]
};
// 版本二内存优化直接以原数组为dp数组
var uniquePathsWithObstacles = function(obstacleGrid) {
const m = obstacleGrid.length;
const n = obstacleGrid[0].length;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (obstacleGrid[i][j] === 0) {
// 不是障碍物
if (i === 0) {
// 取左边的值
obstacleGrid[i][j] = obstacleGrid[i][j - 1] ?? 1;
} else if (j === 0) {
// 取上边的值
obstacleGrid[i][j] = obstacleGrid[i - 1]?.[j] ?? 1;
} else {
// 取左边和上边的和
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
} else {
// 如果是障碍物则路径为0
obstacleGrid[i][j] = 0;
}
}
}
return obstacleGrid[m - 1][n - 1];
};
```
### TypeScript
```typescript