Lintcode—跳跃游戏

来源:互联网 发布:美国gdp数据 编辑:程序博客网 时间:2024/05/06 00:49

跳跃游戏(Java)

题目

给出一个非负整数数组,你最初定位在数组的第一个位置。数组中的每个元素代表你在那个位置可以跳跃的最大长度。判断你是否能到达数组的最后一个位置。

输入:

[2,3,1,1,4]

输出:

true

思路:

从后往前遍历,给每一个位置设置一个标志位,表示能否通过这个位置到达终点。这个标志位的设置,由这个点能否通过排在它后面的点到达终点。有两种可能性:一种是从该点可以直接到达终点,另一种是通过排在后面的标志位为true的点到达终点。

Java代码:

public class Solution {    /**     * @param A: A list of integers     * @return: The boolean answer     */   public static boolean canJump(int[] A) {        // wirte your code here        int n = A.length;        boolean[] canreach = new boolean[n];        canreach[n-1] = true;        for(int i = n-2; i >= 0; i--){              if(A[i] >= (n - 1 - i)){                   canreach[i] = true;                   continue;             }            for(int j = i; j < n-1; j++){                if(canreach[j] && (j - i) <= A[i] ){                        canreach[i] = true;                        continue;                }            }        }        return canreach[0];    }}
0 0