[leetcode] 45. Jump Game II 解题报告

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


本题是一个动态规划题目,保存一个最大可到达的距离,并设置一个数组来保存到达每个位置最短的步数,即当前的位置加上当前最大可走的步数,如果本次更新了最大距离,则同样更新从上一个最大距离到这次最大距离之间位置的步数,要注意边界条件,就是最大到达距离超出了数组长度的时候要做一个判断。

代码如下:

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值