[leetcode]45. Jump Game II 跳棋游戏2 C++/PYTHON实现【hard难度】

题目

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

翻译一下 是jump gamehttp://blog.csdn.net/zl87758539/article/details/51694895那个题目派生出来的。
之前那个是问你能不能跳到最后一个,现在是给你一个数组,肯定能跳到最后,问你最少需要多少步。

其实思路差不多的,之前用贪心,比如说n个数,第i个数跳的最远记下来, G=max(G,nums[i]+i)
现在肯定也要记,只不过是,记每一步跳的最远,我们设一个 Gstep 也可以简称 Gs ,所需要的步数为 R ,就以 A=[2,3,1,1,4] 举例,
第0个位置,最远能跳到2, G=2,Gs=2,R=1
第1个位置 A1=3 ,这下最远能跳到4,好 G=4 但是先别急,依然有 Gs=2 ,因为这一步还没走完,
第2个位置 A2=1 的时候,这个时候 如果从第0个位置跳,显然跳不过来,需要再加一步, R=R+1=2 ,这个时候,, Gs, 也需要更新了,就是第二步我们跳多远的问题,根据贪心算法,我们跳所能跳的最远也就是 Gs=G=4, 这样就到结尾了。return R =2

代码如下:
C++

class Solution {
public:
    int jump(vector<int>& nums) {
        int L = nums.size();
        if (L == 0 ||L ==1)return 0;
        int G = nums[0],Gstep = G,R=1;
        for(int i = 1;i < L -1; i++){
            G = max((nums[i]+i),G);
            if(i>=Gstep){
                Gstep=G;R++;
            }
            if(Gstep>=L-1)return R;
        }
        return R;
    }
};

PYTHON



class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        L = len(nums)
        if L in [0,1]:
            return 0
        G = nums[0]
        Gs = G
        R = 1
        for i in range(1,L-1):
            G=max(nums[i]+i,G)
            if i >= Gs:
                Gs = G
                R+=1   
            if Gs>=L-1:
                return R
        return R

“`

你可能感兴趣的:(leetcode,python,C++)