您的位置:首页 > 其它

Leetcode: Jump Game

2013-10-29 11:16 309 查看
http://oj.leetcode.com/problems/jump-game/

class Solution {
public:
// Don't code too fast
// The bad dp algorithm below (commented out) has the complexity of O(N*N)
/*bool search(int A[], int n, int current, vector<int> &dp){
if(dp[current]!=-1) return dp[current]==1;
dp[current]=0;
for(int last=min(n-1, current+A[current]);last>current;last--){
if(search(A,n,last,dp)){
dp[current]=1;
break;
}
}
return dp[current]==1;
}
bool canJump(int A[], int n) {
vector<int> dp;
// -1 unknown  0 unreachable 1 reachable
for(int i=0;i<n-1;i++) dp.push_back(-1);
dp.push_back(1);
return search(A,n,0,dp);
}*/
bool canJump(int A[], int n) {
int lowestIndex=n-1;
for(int i=n-2;i>=0;i--){
if((i+A[i])>=lowestIndex) lowestIndex=i;
}
return lowestIndex==0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: