Jump Game

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(int A[], int n) {
        vector<int> step(n,0);
        step[0] = 1;
        int temp=0;
        int maxl = 0;

        for(int i = 0 ; i < n ; i++)
        {
            if(step[i] == 0)continue;
            for(int j = maxl ; j <=i+ A[i] ; j++)
            {
                step[j] = 1;
                if(step[n-1] == 1)return 1;
            }
            if(maxl < i+A[i]) maxl = i+A[i];
        }
        return 0;
        
    }
};

  

原文地址:https://www.cnblogs.com/pengyu2003/p/3595292.html