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.

先尝试DFS,大数据的时候果然TLE.仔细看,中间有大量的重复的步骤,比如:[2] 这个节点可能的情况是 step = 1 or step = 2,这种情况在

3 step = 12之后,又进行了一次. 复杂度很大,都和取值有关系

dp[i] 表示从 0 i是否可达到:dp[i] = {dp[0]..dp[j]..dp[i-1]  if  dp[j] && A[j] >= i-j} dp[0] = true others dp[i] = false;

class Solution {
public:
    bool canJump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<bool> dp(n,false);
        dp[0] = true;
        for(int i = 1; i < n; i++){
            for(int j = 0; j < i; j++){
                if (dp[j] && A[j] >= i - j){
                    dp[i] = true;
                    break;
                }
            }
            //可以提前退出
            if (!dp[i]){
                return false;
            }
        }
        return dp[n-1];
    }
};

 

 

posted @ 2013-07-13 14:35  一只会思考的猪  阅读(148)  评论(0编辑  收藏  举报