【Jump Game】cpp

本文介绍了一种贪心算法的实现方式,用于解决跳跃游戏问题,目标是判断是否能够从数组的第一个元素跳跃到最后一个元素。通过迭代变量和维护一个最大跳跃距离,该算法在 O(n) 时间复杂度和 O(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.

代码:

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

tips:

随手写了一个DFS Solution,结果是对的但是超时,shit...

====================================

由于不会Greedy的算法,一心想写一个dp solution,结果最后dp没写成,写成了个greedy;不过代码还是很简洁和高效的:

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

tips:

算法的时间复杂度O(n),空间复杂度O(1)。

正常往后迭代变量,每次迭代变量后,维护一个max_jump(即走到元素i,已知可以走到最远的元素下标)。

如果下标大于等于nums.size()-1,则返回true;如果遍历到max_jump了,且没有到达nums.size()-1,则返回false。

后来想想能不能用dp或者dfs再解一次,但想来想去,dp或者dfs解法的核心无非还是变形的greedy,没有太大意思。完毕。

===============================================

第二次过这道题,直接写了greedy的AC了。

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

 

转载于:https://www.cnblogs.com/xbf9xbf/p/4539326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值