思路:
class Solution {
public:
bool canJump(vector<int>& nums) {
return dfs(nums,0);
}
bool dfs(vector<int>& nums,int i){
if(i == nums.size()-1) return true;
for(int j = 1; j <= nums[i]; j++){
if(dfs(nums,i+j)) return true;
}
return false; //如果不加这行代码,在有的编译器能够运行(因为程序自动return 0),但leetcode需要显式的返回语句。
}
};
- 如果只是判断能否跳到终点,我们只要在遍历数组的过程中,更新每个点能跳到最远的范围就行了,如果最后这个范围大于等于终点,就是可以跳到。参考
class Solution {
public:
bool canJump(vector<int>& nums) {
int i = 0,reach = 0;
for(i = 0; i <= reach && i < nums.size(); i++){
reach = max(reach,nums[i]+i);
}
return i == nums.size();
}
};