Jump Game

来源:互联网 发布:大连海关数据分中心 编辑:程序博客网 时间:2024/05/01 05:29

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.

思路:刚刚开始的时候,看到网上说用贪心法,每一次选择最最远的步数,思路很混乱,不知道怎么选择,万一每一次选择最远的距离,并不能跳到最后该怎么回溯呢。
用动态规划,用一个变量step来记录在当前位置时所能够走到的最远的位置,遍历一遍数组,step就是从i=0出发能够走到的最远的位置,如果此时step小于n-1说明不管怎么走,都不可能走到数组的最后。否则是可以走到数组的最后的。

public class Solution {    public boolean canJump(int[] nums) {        int n=nums.length;        if(n==0) return false;        int step=nums[0];        for(int i=1;i<=step&&i<n;i++)        {               step=step>(i+nums[i]) ? step : i+nums[i];        }        if(step<n-1) return false;        return true;    }}
0 0