leetcode

题目链接
Description
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.

解题思路
利用动态规划思想,使用一个数组res[i]记录从i点到终点的最短步数,从后往前遍历数组,res[i]=min(1+res[(1->nums[i])+i]),最终结果为res[0]。

示例代码

int jump(vector<int>& nums) {
if (nums.size() <= 1)
    return 0;
vector<int> res(nums.size(), 0);
for (int i = nums.size() - 2; i >= 0; i--)
{
    int minx = 10000;
    if (nums.size() - 1 - i <= nums[i])
        res[i] = 1;
    else
    {
        for (int j = nums[i]; j >= 1; j--)
        {
            minx = min(minx, 1 + res[i + j]);
        }
        res[i] = minx;
    }
}
return res[0];
}