您的位置:首页 > 其它

leetcode || 55、Jump Game

2015-04-01 10:52 337 查看
problem:

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
.

Hide Tags
Array Greedy

题意:从起点跳跃,每次跳跃的最大步数为该位置的数组值,判断能否最后跳到最后一个位置

thinking:

(1)刚开始想到DFS,对每一个到达的结点作深搜,但是由于边界条件较少,时间复杂度会急剧膨胀,不太可行

(2)另外一种方法是采用贪心策略,之前一道Jump Game 题目,求步数的也是采用贪心。思路是,采用A[base+step]+step的加权方式来衡量每一次选择的优劣,判断当跳到第一个0处,能否到达或者超过数组最后一个数字。

这里假设成立的是:每次跳跃选择往最远处跳跃,如果最后能够跳到数组最后一位或者最后一位之后,那么一定存在一种跳跃方式正好跳到最后一位上

这个假设很容易证明是成立的,因为最后一步跳跃可以选择0~step之间的任意一步

code:

class Solution {
public:
bool canJump(int A[], int n) {
if(n==1)
return true;
int index=0;
int _max=0;
while(index<n)
{
if(_max>=n-1)
return true;
if(A[index]==0 )
{
if(_max<n-1)
return false;
else
return true;
}
int tmp=A[index];
int flag=0;
for(int i=1;i<=A[index];i++)
{
if(A[index+i]+i>=tmp)
{
tmp=A[index+i]+i;
flag=i;
}
}
index+=flag;
_max=A[index]+index;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: