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 =
[2,3,1,1,4]
, return true
.
A =
Analysis:
If you can jump to the end of the array from a point i, i will be equivalent to the last point, which means you reach i, you will be reaching the last index of the array. So we can make 'i' last element.
Go from the second last element, change the last element recursively, down to the first element, you will know whether you can go through the array.
[3,2,1,0,4]
, return false
.Analysis:
If you can jump to the end of the array from a point i, i will be equivalent to the last point, which means you reach i, you will be reaching the last index of the array. So we can make 'i' last element.
Go from the second last element, change the last element recursively, down to the first element, you will know whether you can go through the array.
class Solution { public: bool canJump(vector<int>& nums) { int last = nums.size()-1; for(int i = nums.size() - 2;i>=0;i--) { if(i+nums[i] >= last) last = i; } return last == 0; } };