Jump Game

##题目

####Jump Game

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.

##解题思路
该题采用动态规划的思想,定义如下:

定义f(i):是否可以到达第i个节点
f(i)=true,只需满足0~i-1个元素中,存在一个元素j,是的f(j)=true且A[j]+j>=i

Jump Game II是其提高版,同样可以采用动态规划求解。

##算法代码
代码采用JAVA实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public boolean canJump(int[] A) {
if(A==null ||A.length==0)
return true;
boolean[] f=new boolean[A.length];
for(int i=0;i<A.length;i++)
f[i]=false;
f[0]=true;
for(int i=1;i<A.length;i++)
for(int j=0;j<i;j++)
if((A[j]+j)>=i && f[j]==true)
{
f[i]=true;
break; //因为已经判定f[i]为true了,所以后面的不需要进行判定了
}
return f[A.length-1];

}
}

Comments