lintcode: 跳跃游戏 II

 跳跃游戏 II

给出一个非负整数数组,你最初定位在数组的第一个位置。

数组中的每个元素代表你在那个位置可以跳跃的最大长度。   

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

样例

给出数组A = [2,3,1,1,4],最少到达数组最后一个位置的跳跃次数是2(从数组下标0跳一步到数组下标1,然后跳3步到数组的最后一个位置,一共跳跃2次)

解题

Jump1 

终于自己还是没有解决出来

参考链接   理解不透 

public class Solution {
    /**
     * @param A: A list of lists of integers
     * @return: An integer
     */
    public int jump(int[] A) {
        int target = A.length-1;
        int cnt = 0;
        while(target > 0) {
            for(int i=0; i<target; i++) {
                if(i+A[i] >= target) {
                    target = i;
                    cnt++;
                    break;
                }
            }
        }
        return cnt;
    }

}

参考链接2 

这个好理解

public class Solution {
    /**
     * @param A: A list of lists of integers
     * @return: An integer
     */
    public int jump(int[] nums) 
    {
        int ret = 0;
        int curMax = 0;
        int curRch = 0;
        for(int i = 0; i < nums.length; i ++) // 一个一个的扫描
        {
            if(curRch < i)// 跳不到 i位置,选取前面可以跳的最远 位置
            {
                ret ++;
                curRch = curMax;
            }
            curMax = Math.max(curMax, nums[i]+i);// 能够跳到最远的 那个位置 
        }
        return ret;
        
    }

}

Python

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        # write your code here
        if A == None or len(A)<= 1:
            return 1
        MaxJump = A[0]
        subJump = A[0]
        count = 1
        for i in range(1,len(A)):
            if subJump <i:
                count+=1;
                subJump = MaxJump
            MaxJump = max(MaxJump , A[i] + i)
        
        return count 
原文地址:https://www.cnblogs.com/bbbblog/p/5292449.html