题目描述:
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.

思路:

基本的动态规划题目,一个目标index是否能到达,取决于他前面所有的index中,是否存在一个i, 满足i可达,且A[i]的value大于i到index之间的距离,状态转移公式如下:

dp[n] = ∪dp[i] ,  ( i = 0 ~ n – 1 , A[i] >= n – i)

代码:

    bool canJump(int A[], int n) {
        if(n <= 1) return true;
        vector dp;
        dp.resize(n);
        for(int i = 0; i < n; i++) {
            dp[i] = false;
        }
        dp[0] = true;
        for(int i = 1; i < n; i++) {
            for(int j = 0; j < i; j++) {
                int distance = i - j;
                if(A[j] >= distance && dp[j]) {
                    dp[i] = true;
                    break;
                }
            }
        }

        return dp[n-1];
    }