您的位置:首页 > 其它

55. Jump Game

2017-07-22 17:04 155 查看
常规回溯TLE

class Solution {
public:
int ending;
bool canJump(vector<int>& nums) {
ending = nums.size() - 1;
if(!ending) return true;
return go(nums, 0);
}

bool go(const vector<int> &nums, int start){
if(start >= ending)
return true;
if(start + nums[start] >= ending)
return true;
for(int i = nums[start]; i >= 1; --i){
if(go(nums, start + i))
return true;
}
return false;
}
};


低效的染色算法
class Solution {
public:
bool canJump(vector<int>& nums) {
int sz = nums.size();
vector<int> colors(sz, 0);
++colors[0];
for(int i=0; i < sz; ++i){
if(colors[i]){
for(int j = i+1;j < sz && j <= i+nums[i]; ++j)
++colors[j];
}
}
if(colors.back())
return true;
return false;
}
};


高效的神奇算法
class Solution {
public:
bool canJump(vector<int>& nums) {
int rightMost = 0, sz = nums.size();

for(int i = 0; i < sz; ++i){
if(rightMost >= sz - 1)
return true;
if(i > rightMost)
break;
rightMost = max(rightMost, i+nums[i]);
}

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