LeetCode_Can Jump

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 arr[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
      
        bool *f = new bool[n];
        memset(f, 0, sizeof(bool) * n);
    	f[0] = true;
    	for (int i = 1; i < n; ++i)
    	{
    		for (int j = i - 1; j >= 0; --j)
    		{
    			if (f[j] && (i - j <= arr[j]))
    			{
    				f[i] = true;
    				break;
    			}
    		}
    	}
        bool ans = f[n-1];
        delete[] f;
    	return ans;
    }
};



你可能感兴趣的:(LeetCode)