leetcode题目 跳跃游戏系列题目

本文探讨了两个关于数组跳跃的问题:一是求最小跳跃次数到达数组末尾;二是判断是否能够到达数组末尾。提供了两种解法并附带代码实现,包括暴力递归法和计算最远跳跃距离法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目一: 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) {
        vector<int> result;
        nextjump(nums,result,0,0);
        sort(result.begin(),result.end());
        return result[0];
    }
    void nextjump(vector<int>& nums,vector<int>& result,int pos,int jump)
    {
        if(pos>=nums.size()-1)
        {
            result.push_back(jump);
            return;
        }
        for(int i=1;i<=nums[pos];++i)
        {
            nextjump(nums,result,pos+i,jump+1);
        }
    }
};

运行结果: 比较短的测试用例可以通过
这里写图片描述

但是提交到leetcode是TLE
这里写图片描述

看到最后一个测试用例很长,然后单独测试一下。
这里写图片描述
结果是栈溢出,也不奇怪了。

解法二: 参考了左程云的书籍

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

测试结果: 只击败了17%的代码,好忧桑。
这里写图片描述

题目二: 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.

思路: 在一题的基础上修改,若走到某个位置发现之前的所有跳跃点都跳不到该位置则返回false。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int cur=0,next=0,i;
        for( i=0;i<nums.size();++i){
             if(cur<i){
                cur=next;
                if(next<i)
                    return false;
            }
            next=max(next,i+nums[i]);
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值