【leetcode hot 100 55】跳跃游戏
解法一:(递归)第i个位置要跳到第j个位置,得nums[i]>=j-i
。因此倒叙,判断能跳到n-1的位置为location1->能跳到location1的位置为location2-> … ->能跳到0则true。
class Solution {
public boolean canJump(int[] nums) {
// 要跳到第j个位置,nums[i]>=j-i(注意要-i)
int n = nums.length;
// 要跳到n
return canJump_helper(nums, n-1);
}
public boolean canJump_helper(int[] nums, int location){
// location是现在在的位置
if(location==0){
return true;
}
for(int i=0; i<location; i++){
if(nums[i]>=location-i){
// 能跳
return canJump_helper(nums, i);
}
}
return false;
}
}
注意:
- 要跳到第
j
个位置,nums[i]>=j-i
,这里不能是i
,得是i-1
。
解法二:(贪心算法)我们依次遍历数组中的每一个位置,并实时维护最远可以到达的位置。在遍历的过程中,如果 最远可以到达的位置 大于等于数组中的最后一个位置,那就说明最后一个位置可达,我们就可以直接返回 True 作为答案。反之,如果在遍历结束后,最后一个位置仍然不可达,我们就返回 False 作为答案。
贪心算法(Greedy Algorithm)是一种在求解最优化问题时常用的算法策略。其核心思想是在每一步选择中都采取当前状态下最优的选择,以期望最终得到全局最优解。