现在的位置: 首页 > 综合 > 正文

leetcode——Jump Game

2017年12月22日 ⁄ 综合 ⁄ 共 749字 ⁄ 字号 评论关闭

题目:

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.

Determine if you are able to reach the last index.

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

思路:

该题显然可以使用阶段性思想即意味着适用DP去求解,属于非常简单的DP题目了。

首先,看能否达到A[0],这是肯定的。在到达A[0]的基础上,看能否到达A[1],而这要看从A[0]能否到A[1],即该元素之是不是够大。

适用B数组来记录A的跳转情况(true || false)

那么可知道状态转移公式:B[j] = (B[j-1] && A[j-1]>=1)||(B[j-2] && A[j-2]>=2)||(B[j-3] && A[j-3]>=3).......

以此类推。因此,该题的时间复杂度是O(n^2 )。

如果使用递归的话,该题的复杂度就高了。

AC代码:

public boolean canJump(int[] A) {
        if(A==null ||A.length==0)
            return true;
        boolean[] B = new boolean[A.length];
        B[0]= true;
        for(int i=1;i<B.length;i++){
            for(int j = i-1;j>=0;j--){
                if(B[j] && A[j]>=i-j){
                    B[i] = true;
                    break;
                }
            }
        }
        return B[B.length-1];
    }

抱歉!评论已关闭.