【ATT】Jump Game II

 

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

A: maxpos: 记录当前能够到达的最大位置。

 每次按最大step,向后扩散。

    int jump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> cnt(n);
        
        cnt[0] = 0;
        int maxpos = 0;
        int pos;
        
        for(int i=0;i<=maxpos;i++)
        {
            pos = i+A[i];
            if(pos>n-1)
                pos = n-1;
            if(pos>maxpos)
            {
                for(int j=maxpos+1;j<=pos;j++)
                    cnt[j] = cnt[i]+1;
                maxpos = pos;
            }
            
            if(pos == n-1)
                return cnt[n-1];
        }
        return INT_MAX;
        
    }

  

posted @ 2013-09-29 22:33  summer_zhou  阅读(168)  评论(0编辑  收藏  举报