Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5e1a4b4

Browse files
implement: 55
1 parent 6934f92 commit 5e1a4b4

File tree

1 file changed

+81
-1
lines changed

1 file changed

+81
-1
lines changed

‎src/jump-game/res.js‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44
* @param {number[]} nums
55
* @return {boolean}
66
*/
7+
8+
/**
9+
* 贪心:从右向左迭代,对于每个节点我们检查是否存在一步跳跃可以到达 GOOD 的位置(currPosition + nums[currPosition] >= leftmostGoodIndex)。如果可以到达,当前位置也标记为 GOOD ,同时,这个位置将成为新的最左边的 GOOD 位置,一直重复到数组的开头,如果第一个坐标标记为 GOOD 意味着可以从第一个位置跳到最后的位置。
10+
* @param {*} nums
11+
*/
712
var canJump = function(nums) {
813
let lastPos = nums.length - 1;
914
for (let index = nums.length - 1; index >= 0; index--) {
@@ -14,4 +19,79 @@ var canJump = function(nums) {
1419
}
1520

1621
return lastPos === 0;
17-
};
22+
};
23+
24+
/**
25+
* 回溯法:从第一个位置开始,模拟所有可以跳到的位置,然后从当前位置重复上述操作,当没有办法继续跳的时候,就回溯。
26+
* @param {*} nums
27+
*/
28+
const canJump = (nums) => {
29+
const jumpAnalysis = (index) => {
30+
if (index === nums.length-1) return true;
31+
32+
const maxLen = Math.min(index + nums[index], nums.length-1);
33+
for (let i = index + 1; i <= maxLen; i++) {
34+
if (jumpAnalysis(i)) return true;
35+
}
36+
return false;
37+
}
38+
39+
return jumpAnalysis(0);
40+
}
41+
42+
/**
43+
* 动态规划:自顶向下
44+
* @param {*} nums
45+
*/
46+
const canJump = (nums) => {
47+
const mem = nums.map(() => -1);
48+
mem[nums.length - 1] = 1;
49+
50+
const jumpAnalysis = (index) => {
51+
// 当前元素位置如果已经计算过则返回结果
52+
if (mem[index] !== -1) {
53+
return mem[index] === 1 ? true : false;
54+
}
55+
56+
// 未计算的位置根据可走步数更新 mem
57+
const maxLen = Math.min(index + nums[index], nums.length-1);
58+
for (let i = index + 1; i <= maxLen; i++) {
59+
// 如果当前位置已可以跳到结果那么提前结束返回结果
60+
if (jumpAnalysis(i)) {
61+
mem[i] = 1;
62+
return true;
63+
}
64+
}
65+
66+
// 标定当前位置无用
67+
mem[index] = 0;
68+
return false;
69+
}
70+
71+
return jumpAnalysis(0);
72+
}
73+
74+
/**
75+
* 动态规划:自底向上
76+
* @param {*} nums
77+
*/
78+
const canJump = (nums) => {
79+
const len = nums.length;
80+
if (!len) return false;
81+
if (len === 1) return true;
82+
const mem = nums.map(() => 0);
83+
mem[nums.length - 1] = 1;
84+
85+
for (let i = nums.length - 2; i >= 0; i--) {
86+
const maxLen = Math.min(i + nums[i], nums.length-1);
87+
for (let j = i+1; j <= maxLen; j++) {
88+
if (mem[j]) {
89+
mem[i] = 1;
90+
break;
91+
}
92+
}
93+
}
94+
95+
return mem[0] === 1;
96+
}
97+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /