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
.
给定一个数组,数组中每一位的值表示你从这个位置可以向前跳的最大距离。判断能否从第一个经过若干次跳转之后到达最后一个位置
思路跟Jump Game II相同,参见Jump Game II。
class Solution { public: bool canJump(int A[], int n) { if(n<0)return false; if(n==1)return true; int pos=1; //指向还没有标记最小跳转步数的第一个位置 int*minStep=new int[n]; for(int i=0; i<n; i++)minStep[i]=0; for(int i=0; i<n-1; i++){ while(pos<n && pos<=i+A[i] && pos>i){ //注意pos>i的条件,在能正常跳转的情况下,pos一定在当前起跳位置i之后 minStep[pos++]=minStep[i]+1; } } int distinationStep=minStep[n-1]; return distinationStep!=0; } };
LeetCode: Jump Game [054],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26741677