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
.
class Solution { bool do_once(vector<int>&candi,vector<int>&nums,set<int>&history) { vector<int>newcandi; for (int i = 0; i < candi.size(); i++) { for (int j = candi[i]; j < nums.size(); j++) { if (nums[j] == 0) { if (j == nums.size() - 1) return true; int jj = j; while (jj < nums.size() && nums[jj] == 0) jj++; for (int h = candi[i]; h < j; h++) { if (nums[h] >= jj - h-1 ) { if (nums[h]>=nums.size() - 1 - h) return true; int bb = jj; while (bb <= h + nums[h]) { int bbb = bb; while (bb <= h + nums[h] && nums[bb] > 0) bb++; if (history.find(bbb) == history.end()) { newcandi.push_back(bbb); history.insert(bbb); } while (bb <= h + nums[h] && nums[bb] == 0) bb++; } } } break; } else if (j == nums.size() - 1) return true; } } candi = newcandi; return false; } public: bool canJump(vector<int>& nums) { if (nums.empty() || nums[0] == 0&&nums.size()>1) return false; if (nums[0] == 0 && nums.size() == 1) return true; /*vector<int>zeropos; for (int i = 0; i < nums.size(); i++) if (nums[i] == 0) zeropos.push_back(i);*/ bool f = false; vector<int>candi; candi.push_back(0); set<int>history; while (!f&&!candi.empty()) { f = do_once(candi, nums, history); } return f; } };