55. Jump Game

本文介绍了一个经典的算法问题——跳跃游戏。通过分析问题背景,提出了一种高效的贪心算法解决方案,并详细解释了其实现思路和步骤。该算法的目标是判断能否从数组的起始位置达到末尾。

摘要生成于 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.
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.

This is a dynamic programming[1] question. Usually, solving and fully understanding a dynamic programming problem is a 4 step process:
  1. Start with the recursive backtracking solution
  2. Optimize by using a memoization table (top-down[3] dynamic programming)
  3. Remove the need for recursion (bottom-up dynamic programming)
  4. Apply final tricks to reduce the time / memory complexity
All solutions presented below produce the correct result, but they differ in run time and memory requirements.

第一次就直接写出了3 还不错 这里的贪心算法不是很难 可以看看

public boolean canJump(int[] nums) {
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }

每次尝试最右的点 跳最大步数 看是否能达到 lastPos
一开始纠结会不会忽略情况 比如
5 3 2 1 4
1可以到达4 2也可以 1会被作为lastPos 那后面就是找能到达1的点 会不会忽略到达2的情况 实际是不会的 
2可以到达4 那就可以到达1 所以2就会被选作下一次的lastPos
相当于2->4被拆成了 2->1->4 大步被拆成小步 最终效果是一样的


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值