LeetCode- Jump game

本文解析了跳跃游戏I的问题,介绍了两种解决方法:贪心算法和动态规划。通过具体实例阐述了算法实现过程,并提供了C++代码示例。

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

jump game I

1 . 题目描述

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.

中文阐述:给出一个非负整数数组,你最初定位在数组的第一个位置。   

数组中的每个元素代表你在那个位置可以跳跃的最大长度。    

判断你是否能到达数组的最后一个位置。

A[0]可以跳到A[1]A[2],跳到A[2],最多跳1步,到A[3],最多跳一步,到A[4],最多跳一步,到A[5].true
A[0]到A[3],A[3]去不了。第二个例子false。


思路阐述

1. 贪心

依次遍历数组,求每一步所能达到的最远位置的最大值
1. 这个最大值如果大于或等于n - 1,则表示一定能达到最后一个位置。
2. 而如果在遍历过程中,发现某个位置(数组下标)大于最远位置了,那也就是说不可能到达这个位置,当然就不可能到达最后了;

比如样例中第二个例子:
1. 扫描到3,far = 0 + 3
2. 扫描到2,far = max(3, 1 + 2) = 3
3. 扫描到1,far = max(3, 2 + 1) = 3
4. 扫描到0,far = max(3, 3 + 0) = 3
5. 扫描到4,此时,数组下标为4,4 > 3,失败


2. 动态规划

设状态为 f[i],表示从第 0 层出发,走到 A[i] 时剩余的最大步数,则状态转移方程为:f[i] = max(f[i − 1], A[i − 1]) − 1, i > 0代码 1// LeetCode, Jump Game// 思路 1,时间复杂度 O(n),空间复杂度 O(1)


依次遍历数组,设maxJump为当前最远能跳到的距离。
1. 如果i+maxJump>=n-1说明true
2. 若maxJump=0说明没办法跳了,为false.
3. 每走一步,即i++时,maxJump-=1。


代码

代码一(对应贪心算法)

class Solution{
    public:
        bool canJump(int A[], int n) {
            int max = 0;
            for(int i = 0; i < n; i++) {
                if(i > max) return false;
                int nowMax = i + A[i];
                if(nowMax > max) max = nowMax;
            }
            return true;
        }
};

代码二(动态规划)

class Solution {
public:
    bool canJump(int A[], int n) {
        if (n == 1) return true;
        int maxJump =0;//current you can jump
        for (int i = 0; i < n; i++){
            maxJump--;
            if (maxJump < A[i])
                maxJump = A[i];

            if (!maxJump)
                return false;

            if (maxJump + i >= n - 1 )
                return true;
        }
        return false;
    }
};

4. 下一篇

下一篇是jump game II 参见我的博客列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值