题目链接:
https://leetcode.com/problems/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.
这个题的要求是给定一个整数数组,数组元素表示在某一位置能够跳跃的最大距离。求知从0跳跃到最后位置的最小次数。(忽略能否跳跃到最后)
https://leetcode.com/problems/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.
这个题的要求是给定一个整数数组,数组元素表示在某一位置能够跳跃的最大距离。求知从0跳跃到最后位置的最小次数。(忽略能否跳跃到最后)
思路:动态规划。
class Solution {
public:
int jump(vector<int>& nums) {
int size = nums.size();
int *step = new int [size];
vector<int> res = vector<int>(0);
int pos = 0;
for (int i =0; i < size; i++)
{
if (i+nums[i] > pos)
{
for (int j = pos+1; j <= i+nums[i] && j < size; j++)
{
step[j] = i;
}
pos = i +nums[i];
}
}
int ans = 0;
int p = size-1;
while (p > 0)
{
p = step[p];
ans++;
}
return ans;
}
};