[leetcode] 55. Jump Game

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

分析一

题目的意思是:给你一个数组,数组的值代表能够跳跃的最大范围,现在问能否从开始跳到数组末尾。

  • 动态规划的解法,dp[i]表示到达i时剩余的步数,当前位置的剩余步数和当前位置的跳力较大的那个数决定了当前能到的最远距离。而下一个位置的剩余步数就等于较大值减去1,因为需要花费一个跳力到达下一个位置。状态转移方程为:
    dp[i]=max(dp[i-1],nums[i-1])-1;

代码一

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

分析二

  • 见代码注释

代码二

class Solution {
public:
    bool canJump(int A[], int n) {
        int max_val=0; //max_val标记能跳到的最远处。
        for(int i=0;i<n&&i<=max_val;i++){ //max_val>=i表示此时能跳到i处,0<=i<n表
            max_val=max(max_val,A[i]+i);  //示扫描所有能到达的点,在改点处能跳到的最远处。
        }
        if(max_val<n-1){ //如果最后跳的最远的结果大于等于n-1,那么满足,能跳到最后,否则,不能。
            return false;
        }
        return true;
    }
  
};

Python 代码 贪心实现

cur_reach表示从当前位置还能走的最大步数,初始化为1,每遍历一次,要减去1,通过nums的位置的最大步数来更新cur_reach的最大步数。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        cur_reach=1
        for i in range(len(nums)):
            cur_reach-=1
            if cur_reach<0:
                return False
            else:
                cur_reach=max(cur_reach,nums[i])
        return True

Python DP实现

这里递推公式很好写,要注意一些corner case, 比如[2,0], [2,0,0]这种情况是可以pass的。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        # dp[i]=max(dp[i-1],nums[i-1])-1
        # dp[0]=nums[0]
        n = len(nums)
        dp = [0]*(n)
        dp[0]=nums[0]
        for i in range(1,n):
            dp[i]=max(dp[i-1],nums[i-1])-1
            if dp[i]<0:
                return False
        return dp[n-1]>=0

参考文献

[编程题]jump-game
[LeetCode] Jump Game 跳跃游戏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值