LeetCode每日一题:jump game i

2017-06-09  本文已影响8人  yoshino

问题描述

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[i]表示A[i]可达,那么dp[i]~dp[i+A[i]]均可达,最后注意i+A[i]是否大于A.length()即可。

代码实现

public boolean canJump(int[] A) {
        if (A.length == 0) return false;
        boolean[] dp = new boolean[A.length];
        dp[0] = true;
        for (int i = 0; i < A.length; i++) {
            if (dp[i] == true) {
                for (int j = 1; j <= A[i]; j++) {
                    if (i + j < A.length) dp[i + j] = true;
                    else return true;
                }
            }
        }
        return dp[A.length - 1];
    }
上一篇 下一篇

猜你喜欢

热点阅读