LeetCode week 6 : Jump Game

题目

地址:
https://leetcode.com/problems/jump-game/description/
类别: Greedy
难度: Medium
描述:
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.

分析

题目要求根据非负数组中的元素判断能否跳到最后元素位置,其中数组中的每个元素表示当前位置向后跳跃的最大步数,起点位于数组起始位置,若能经过一系列跳跃到达最后位置则返回true,否则返回false。

解决

思路一

正向跳跃:定义reach为最远可达位置,初始化为0,然后遍历每一个点,若当前点可达最大位置比reach大,则更新reach为当前点可达最大位置。

成功条件:在遍历到某个位置时reach >= len(nums)-1,即能跳到最后一点。
失败条件:在遍历到某位置i-1时,reach < i,即i点之前的点都无法跳到i点及其之后的位置,跳跃失败终止。

代码实现

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

反向回溯:与正向跳跃思路类似,只是方向相反。若能从某一点i跳到最后位置,那只需解决从起点跳到i点这个子问题即可,最后看是否能回溯到起点。
代码实现

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int last = nums.size()-1, i, j;
        for(i = nums.size()-2; i >= 0; i--){
            if(i + nums[i] >= last) last = i;
        }
        return last<=0;
    }
};
思路三

判断“0”点:可以观察到若一个数组不含0,那么一定可以到达最后位置,因为我们只需每次跳跃当前位置数值步数即可。如果出现了0点(只考虑出现在最后位置之前的)的话,我们只需判断能否跳过此点即可, 若能跳过此点,那么此点后面的非0部分一定都可达。

若i(i不为最后位置)点处nums[i] = 0,则依次遍历i点之前的点:
1.若某点j能跳过i点即i - j < nums[j],则跳跃此零点成功;
2.若i点之前的点都跳不过i点,则跳跃中断于i点失败。

如上遍历完所有零点位置,若都成功,则最后成功;若有一处失败,则最后失败。

代码实现

class Solution {
public:
    bool canJump(vector<int>& nums) {
        for(int i = nums.size() - 1; i >= 0; i--) {
            if(nums[i] == 0 && i != nums.size() - 1) {
                int j = i;
                while(j >= 0) {
                    if(i - j < nums[j]) {
                        break;
                    }
                    j--;
                }
                if(j < 0) return false;
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值