0
点赞
收藏
分享

微信扫一扫

LeetCode-45. Jump Game II

c一段旅程c 2022-08-10 阅读 66


Given an array of non-negative integers, 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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

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

题解:

动态规划超时。

dp:

class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n == 0 || n == 1) {
return 0;
}
vector<int> dp(n, n);
dp[0] = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j <= nums[i]; j++) {
if (i + j < n) {
dp[i + j] = min(dp[i + j], dp[i] + 1);
}
}
}
return dp[n - 1];
}
};

bfs:

记录每个点能到达的最大值,记为preMax,然后在该范围内寻找nextMax,即这个范围内能到达的下一个最大值,遍历到preMax时,当前步伐数++。返回到达终点时最小步伐。

class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n < 2) {
return 0;
}
int prev = nums[0], next = nums[0], step = 1;
for (int i = 1; i < n; i++) {
if (prev >= n - 1) {
return step;
}
if (i > prev) {
step++;
prev = next;
}
next = max(i + nums[i], next);
}
return step;
}
};

 

 


 

举报

相关推荐

0 条评论