Jump Game I&&II——入门级贪心算法

本文详细介绍了贪心算法在解决跳跃游戏问题中的应用,包括如何通过记录数组中每个元素可以移动的最大位置来判断是否能到达最后一个索引。同时,文章提供了两个不同版本的跳跃游戏解决方案:JumpGameI 和 JumpGameII,分别关注于判断是否可达和最小跳跃次数。通过清晰的代码实现,展示了贪心策略在实际问题解决中的高效性和简洁性。

Jump Game I

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

说是贪心算法,其实就是记录数组中每个元素可以移动的最大位置。之前思路不太清晰,写代码一定要有清晰的思路啊,而且想问题应该要从多个角度去想才对。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int size=nums.size();
       // int flag=0;
        if(size==1)
            return 1; 
        int maxstep=nums[0];
        for(int i=1;i<size;i++)
        {
            if(maxstep==0)
                return 0;
            maxstep--;
            maxstep=max(maxstep,nums[i]);
            
        }
        return 1;
        
    }
};

 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.

仍然使用贪心,只不过是要记录当前一跳所能到达的最远距离、上一跳所能达到的最远距离,和当前所使用跳数就可以了代码如下:

class Solution {
public:
    int jump(vector<int>& nums) {
        int len=nums.size();
        int cur=0;
        int last=0;
        int res=0;
        for(int i=0;i<len;i++)
        {
            if(i>cur)
                return -1;
            if(i>last)
            {
                last=cur;
                res++;
            }
            cur=max(cur,i+nums[i]);
        }
         return res;
    }
};
  

 

转载于:https://www.cnblogs.com/qiaozhoulin/p/4521661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值