码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - Jump Game II

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

标签:c++   程序员   面试   贪婪   

题目:

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

标签:c++   程序员   面试   贪婪   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!