Skip to content

Commit 3cbf76e

Browse files
author
tanjiasheng
committed
Unique Paths II
1 parent df286c4 commit 3cbf76e

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

Unique Paths II/index.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[][]} obstacleGrid
3+
* @return {number}
4+
*/
5+
function uniquePathsWithObstacles(obstacleGrid) {
6+
const m = obstacleGrid.length;
7+
const n = obstacleGrid[0].length;
8+
9+
// 存放到达每一格的路线数量
10+
const solutionMap = [];
11+
12+
for (let i = 0; i < m; i++) {
13+
if (!solutionMap[i]) solutionMap[i] = [];
14+
for (let j = 0; j < n; j ++) {
15+
if (i === 0 && j === 0) {
16+
solutionMap[0][0] = 1 - obstacleGrid[0][0];
17+
} else {
18+
if (obstacleGrid[i][j]) {
19+
solutionMap[i][j] = 0;
20+
} else {
21+
solutionMap[i][j] =
22+
(i >= 1 ? solutionMap[i - 1][j] : 0)
23+
+ (j >= 1 ? solutionMap[i][j - 1] : 0);
24+
}
25+
}
26+
}
27+
}
28+
29+
return solutionMap[m - 1][n - 1];
30+
};

Unique Paths II/index1.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// 对已计算过的结果做缓存
2+
let solutionMap;
3+
4+
/**
5+
* @param {number[][]} obstacleGrid
6+
* @return {number}
7+
*/
8+
function uniquePathsWithObstacles(obstacleGrid) {
9+
const m = obstacleGrid.length;
10+
const n = obstacleGrid[0].length;
11+
12+
solutionMap = new Map();
13+
// 调用递归计算方法
14+
return solution(m - 1, n - 1, obstacleGrid);
15+
};
16+
17+
// 走到坐标为(x, y)有多少种走法
18+
function solution(x, y, obstacleGrid) {
19+
const isObstacle = obstacleGrid[x][y] === 1;
20+
21+
// 边缘情况处理
22+
// 当前格子是障碍物,直接返回0
23+
if (isObstacle) return 0;
24+
25+
// (1, 0)和(0, 1)的情况
26+
if ((x === 0 && y === 1) || (x === 1 && y === 0)) return 1 - obstacleGrid[0][0];
27+
28+
// (0, 0)的情况
29+
if (x === 0 && y === 0) return 1;
30+
31+
// 非障碍物,递归计算
32+
// 到左面一格的走法数量
33+
const leftSolution = y - 1 >= 0 ? getSolution(x, y - 1, obstacleGrid) : 0;
34+
35+
// 到上面一格的走法数量
36+
const topSolution = x - 1 >= 0 ? getSolution(x - 1, y, obstacleGrid) : 0;
37+
38+
const result = topSolution + leftSolution;
39+
40+
// 设置缓存
41+
solutionMap.set(x + '' + y, result);
42+
43+
return result;
44+
}
45+
46+
// 判断若在缓存中出现,则直接返回缓存结果,否则调用solution方法计算
47+
function getSolution(x, y, obstacleGrid) {
48+
return solutionMap.get(x + '' + y) || solution(x, y, obstacleGrid);
49+
}

Unique Paths II/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
动态规划,
2+
第一种是循环,从左上角开始,每一格的解都是它的上面那格和左边那格的和,循环遍历求解,
3+
第二种是递归,f(x, y)是(0, 0)到(x, y)的路线数,由于到达每一个点有从它的上面一格往下走一格或者从左边一格往右走一格两种情况,即f(x, y) = f(x, y - 1) + f(x - 1, y)

0 commit comments

Comments
 (0)