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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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.

code

//Greedy:Looking from the start and selecting the locally optimum in the hope of reaching global optimum
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    bool canJump(vector<int>& nums)
    {
        if(nums.empty())
            return false;

        int i=0;
        for(int reach=0;i<=reach&&i<nums.size();++i)
        {
            if(reach<i)
                return false;
            reach=max(i+nums.at(i),reach);
        }
        return i==nums.size();
    }
};
int main()
{
    vector<int> arr{2,3,1,0,4};
    Solution s;
    cout<<s.canJump(arr)<<endl;
    return 0;
}

dp:

//dp:Looking from the end and at each point ahead checking the best possible way to reach the end
class Solution
{
public:
    bool canJump(vector<int> &nums)
    {
        if(nums.empty())
            return false;

        vector<bool> flag(nums.size(),false);
        flag.at(nums.size()-1)=true;
        for(int i=nums.size()-2;i>=0;--i)
        {
            for(int j=0;j<=nums.at(i);++j)
            {
                if(flag.at(i+j)==true)
                {
                    flag.at(i)=true;
                    break;
                }
            }
        }
        return flag.at(0);
    }
};

  Jump Game 随笔

If we have a Greedy Approach here then we will take the path 1+99+1 as we select local optimum from the beggining

But if we take DP Approach then we start from back and find the cost of reaching end from that specific node. So when we reach the first node we will have two options

 

    1. 99+1 path
    2. 5+1 path
      Now we simply have to decide between (1+(99+1)) and (20+(5+1)) path
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄