美文网首页
LeetCode 45. Jump Game II

LeetCode 45. Jump Game II

作者: cb_guo | 来源:发表于2019-04-10 18:45 被阅读0次

    题目描述

    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.

    Example:

    Input: [2,3,1,1,4]
    Output: 2
    Explanation: 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.
    

    Note:
    You can assume that you can always reach the last index.

    题目思路

    • 思路一、递归实现,超时。测试用例 71/92
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int len = nums.size();
            return fab(nums, len, 0);
        }
        
        int fab(vector<int>& nums, int& len, int k){
            if(k >= len-1)  return 0;
            
            if(nums[k] == 0) return -1;
            
            int tt = 0;
            int uu = 0;
            bool flag = true;
            for(int i=1; i <= nums[k]; i++){
                uu = fab(nums, len, k+i);
                if(uu == -1) continue;            
                
                if(flag)
                    tt = uu;
                else
                    tt = tt > uu ? uu : tt;
                flag = false;
                
            }
            return tt+1;
        }
    };
    
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int len = nums.size();
            int step = 0, start = 0, end = 0;
            while(end < len-1){
                step += 1;
                int temp = end + 1;
                for(int i=start; i <= end; i++ ){
                    if(i+nums[i] >= len-1) return step;
                    temp = max(temp, i+nums[i]);
                }
                start = end+1;
                end = temp;
            }
            return step;
        }
    };
    

    总结展望

    相关文章

      网友评论

          本文标题:LeetCode 45. Jump Game II

          本文链接:https://www.haomeiwen.com/subject/wlvniqtx.html