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 =
A =
自己的思路:从前往后扫描,设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);
}
};
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 55 Jump Game(Python 实现及详解)
- leetcode55 Jump Game
- LeetCode 55(Jump Game) Java
- LeetCode 55 Jump Game
- LeetCode 55 --- Jump Game
- LeetCode-55-Jump Game 贪心水题
- 【leetcode】Array——Jump Game(55)
- LeetCode(55) Jump Game
- [LeetCode] 55. Jump Game
- LeetCode 55 Jump Game
- LeetCode 55: Jump Game
- leetcode_question_55 Jump Game
- leetcode——55——Jump Game
- [leetcode 55] Jump Game
- leetcode-55 Jump Game
- 【LeetCode】C# 55、Jump Game
- 第六周:(LeetCode 45 55) Jump Game I II(c++)
- [LeetCode]55 Jump Game
- Leetcode 55 Jump Game(第七周作业)
- [LeetCode 55] Jump Game