【ATT】Jump Game

Q:

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.

A: 贪心策略。step,记录当前能够走的最大步数,初始化step = A[0],到下一步step--, 并且取step = max(step, A[1]),这样step一直是保持最大的能移动步数,局部最优也是全局最优。

    bool canJump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n==0)
            return false;
        
        int step = A[0];
        
        for(int i=1;i<n;i++)
        {
            if(step>0)
            {
                step--;
                step = max(step,A[i]);
            }else
                return false;
        }
        
        return true;
        
    }

  

 

    bool canJump(int A[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(n<=0)
            return true;
        int curstep = A[0];
        
        for(int i=1;i<n;i++)
        {
            if(curstep==0)
                return false;
            curstep--;
            curstep = max(curstep,A[i]);
        }
        return true;
        
    }

  

posted @ 2013-09-18 12:55  summer_zhou  阅读(218)  评论(0编辑  收藏  举报