LeetCode 45. Jump Game II

2019-04-10  本文已影响0人  cb_guo

题目描述

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.

题目思路

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;
    }
};

总结展望

上一篇 下一篇

猜你喜欢

热点阅读