LeetCode 55 跳跃游戏

Leetcode 55 跳跃游戏

解题思路:

这个题典型的贪心算法,不过一开始我用的递归法,结果递归栈爆掉了,我查了一下那个超时的测试用例,结果如下:
在这里插入图片描述
当我看到这个测试数据,我整个人都裂开了。。。于是求助了大神的思路,真的是太简洁了。。。

  1. 整体将所有的step遍历一次,cindex记录了当前的索引位置,jump_length记录了这个人所能跳的最远距离(注意,如果当前位置比这个人所能跳的最远距离还大,说明这个人已经不能到达当前的位置了,因为跳不过来,所以以后的所有位置也注定跳不过去,此时直接返回false就可以了,否则要对最远距离进行更新)
  2. 如果所有的位置都遍历结束,并且这个人可以到达终点的话,就可以结束了。
递归法的源代码:
class Solution {
private:
    vector<int> tmp_nums;
public:
    bool can(int cindex,int step,int len){
        if(cindex + step >= len){
            return true;
        }
        int i;
        bool judge = false;
        for(i=1;i<=step;i++){
            if(tmp_nums[cindex + i] != 0){
                judge = can(cindex + i,tmp_nums[cindex + i],len);
            }
            if(judge){
                break;
            }
        }
        return judge;
    }
    bool canJump(vector<int>& nums) {
        this->tmp_nums = nums;
        bool judge_result = false;
        judge_result = can(0,nums[0],nums.size()-1);
        return judge_result;
    }
};
源代码:
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int jump_length = nums[0];
        int cindex;
        for(cindex = 0;cindex < nums.size();cindex ++){
            if(jump_length < cindex){
                return false;
            }
            jump_length = max(jump_length,nums[cindex] + cindex);
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值