45. Jump Game II
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.
For example:
Given array A = [2,3,1,1,4]
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.
题目链接:https://leetcode.com/problems/jump-game-ii/description/
题目大意:数组A中每个数字代表可最多往后跳的步数。求从第一个数字跳到最后一个数字最少需要多少步。
解题思路:dp递推,从当前下标能抵达的最远下标开始往前更新步数,步数更新为当前的最少步数+1。
代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n == 0 )
return 0;
int dp[n];
int inf = (1 << 31) - 1;
dp[0] = 0;
for(int i = 1;i < n; i++){
dp[i] = inf;
}
for(int i = 0;i < n; i++){
int j = min(i + nums[i],n-1);
for(;j >= i;j--){
if(dp[j] < inf)
break;
dp[j] = min(dp[i] + 1,dp[j]);
}
}
return dp[n-1];
}
};