Jump Game II

来源:互联网 发布:百度源码 编辑:程序博客网 时间:2024/06/16 00:22

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

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

使用DP方法,java可以正常通过,但是python超时

java

public class Solution {    /*     * @param A: A list of integers     * @return: An integer     */    public int jump(int[] A) {        // write your code here        if (A == null || A.length == 0) {            return -1;        }        // state        int[] f = new int[A.length];        // initialize        f[0] = 0;        for (int i = 1; i < A.length; i++) {            f[i] = Integer.MAX_VALUE;        }        // function        for (int i = 1; i < A.length; i++) {            for (int j = 0; j < i; j++) {                if (f[j] != Integer.MAX_VALUE && A[j] + j >= i) {                    f[i] = Math.min(f[j] + 1, f[i]);                }            }        }        // answer        return f[A.length - 1];    }}

python

class Solution:    """    @param: A: A list of integers    @return: An integer    """    def jump(self, A):        # write your code here        if A is None or len(A) == 0:            return -1        # state and initialize        f = [float('inf')] * len(A)        f[0] = 0        # function        for i in range(1, len(A)):            for j in range(i):                if f[j] != float('inf') and A[j] + j >= i:                    f[i] = min(f[j] + 1, f[i])        return f[-1]


原创粉丝点击