Jump Game II

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.)

 

休息一下就做出来了,我能说什么呢……注意边界条件。

class Solution {
public:
    int jump(int A[], int n) {
        vector<int> bo(n,0);
        bo[0]=0;
        int max = 0;
        int count = 0;
        int last = 0 , now = 0;
        if(n==1)return 0;
        for(int i = 0 ; i <n-1 ;)
        {
            max = i+A[i];
            count++;
            if(max >= n-1)return count;
            int oldlast = last;
            last = i;
            for(int j =oldlast+1 ; j < i ; j++)
            {
                if(j + A[j] > max)
                {
                    last = j;
                    max = j + A[j];
                }
            }
            i =max;
        }
        return count;
    }
};

  

posted on 2014-04-19 22:12  pengyu2003  阅读(129)  评论(0编辑  收藏  举报

导航