1. 程式人生 > >[leetcode]45. Jump Game II 跳棋遊戲2 C++/PYTHON實現【hard難度】

[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

“`