首页 > 其他 > 详细

leetcode - Jump Game II

时间:2015-06-29 10:04:48      阅读:81      评论:0      收藏:0      [点我收藏+]

题目:

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(vector<int>& nums) {
        if(nums.size()<=1)
            return nums.size()==1?0:-1;
        if(nums[0]==0)
            return -1;
        int count=0,right=nums[0];//right是能跳到最右边的下标
        for(int i=0;i<nums.size();)
        {
            ++count;//肯定要跳一步
            if(right>=nums.size()-1)//到达终点,结束
                return count;
            int tmp=0,index=-1;
            for(int j=i+1;j<=right;++j)//找到能跳最远的那个下标
            {
               if(tmp<j+nums[j])
               {
                   tmp=j+nums[j];
                   index=j;
               }
            }
            if(tmp<=right)//无法超越上一步,则跳不到终点
                return -1;
            else
            {
                right=tmp;
                i=index;//此行代码确定这一轮循环跳到哪个下标
            }
        }
        return -1;
    }
};


leetcode - Jump Game II

原文:http://blog.csdn.net/bupt8846/article/details/46675869

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!