您的位置:首页 > 其它

LeetCode-55-Jump Game

2015-04-04 09:17 507 查看
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
.

自己的思路:从前往后扫描,设maxlen=A[i]+i,如果A[maxlen]==0,则在i和manlen之间寻找一个坐标index使index+A[index]>maxlen;

代码:

class Solution {
public:
bool jump(int A[],int i,int n){
int maxlen=i+A[i];
if(maxlen>=n-1) return true;
if(A[maxlen]==0){
for(int index=maxlen-1;index>i;index--){
if(A[A[index]+index]!=0) return jump(A,A[index]+index,n);
else if(A[index]+index>maxlen) return jump(A,maxlen+1,n);
}
return false;
}
else return jump(A,maxlen,n);
}
bool canJump(int A[], int n) {
if(n==1) return true;
if(A[0]<1) return false;
bool flag=jump(A,0,n);
if(flag) return true;
else return false;
}
};感觉做的太复杂了,在网上看了其他人的思路,从后往前扫描,感觉比我这好太多了。。。

代码:https://leetcode.com/discuss/25203/14ms-c-o-n-solution

class Solution {
public:
bool canJump(int a[], int n) {
int dest = n-1;
int cur_pos = n-2;
while(cur_pos >= 0 && dest != 0) {
if (a[cur_pos] + cur_pos >= dest) {
dest = cur_pos;
}
cur_pos--;
}
return (dest == 0 ? true : false);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode