[LeetCode] Jump Game II

45. Jump Game II

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

You can assume that you can always reach the last index.

  • new solution update 2022.02.04
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int jump(vector<int>& nums) {
int cur = 0, res = 0, end = 0;
for(int i = 0; cur < nums.size() - 1; i++) {
end = max(end, i + nums[i]);
if(cur == i) {
res++;
cur = end;
}
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int jump(vector<int>& nums) {
vector<int> dp(nums.size());
int maxIdx = 0;
for(int i = 0; i < nums.size() and !dp.back(); i++) {
int maxJump = i + nums[i];
for(int j = maxIdx + 1; j <= maxJump and j < nums.size(); j++) {
dp[j] = 1 + dp[i];
}
maxIdx = max(maxJump, maxIdx);
}
return dp.back();
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int jump(vector<int>& nums) {
vector<int> v(nums.size(), 0);
queue<int> q;
q.push(0);
while(!q.empty() && !v.back()) {
int pos = q.front();
q.pop();
for(int i = min(pos + nums[pos], (int)nums.size() - 1); i > pos; i--) {
if(!v[i]) {
q.push(i);
v[i] = v[pos] + 1;
}
}
}

return v.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/31/PS/LeetCode/jump-game-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.