Leetcode 55. Jump Game

题目

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.

分析

给定一个非负数整数数组,初始位置位于第一个索引处。数组中的每个元素代表能跳动的最大步数。

确定是否能够到达最后一个索引。

例如:

A = [2,3,1,1,4], return true.

解释:

初始位置在A[0],最大能跳动2步,假定跳动最大步数,此时到了A[2] = 1,往前只能跳动一步,

所以到了A[3] = 1,所以正好再向前跳动一步,到达最后一个索引,所以返回为 true。

A = [3,2,1,0,4], return false

解释:

  • A[0] = 3,按照最大跳动步数3,所以调动到了A[3] = 0,此时不能向前跳动,但是未能到达最后

一个索引;

  • 如果在A[0] = 3,不跳动最大步数3,只向前跳动2步,此时到达 A[2] = 1 ,向前跳动一步,

又到了 A[3];

  • 如果 A[0] = 3, 只向前跳动1步,到了A[1] = 2,再向前调动2步或1步,都是到达了 A[3],

所以无论怎么跳动,最后只能到达 A[3],所以返回 false 。

求解方法

利用贪心思想和递归相结合的思路求解本题。

代码

  1 public class Solution {
  2     //[2,2,0,1]
  3     public bool CanJump(int[] nums) {
  4         if(nums.Length==0) return false;
  5         return jump(nums,0,nums[0]);
  6     }
  7 
  8     private bool jump(int[] nums, int cur, int maxjump)
  9     {
 10         if(cur==nums.Length-1)//cur就是终点,直接返回true 
 11             return true;
 12         while(maxjump>0){
 13           int next = cur + maxjump; //cur+maxjump表示为下一次跳的最远位置
 14           if(next >= nums.Length-1) //如果最远位置不小于终点位置,则一定可以到达终点位置,返回true 
 15               return true;
 16             //走到这里表示本次按照最大次数也跳不到终点,那就按照最大步数跳
 17           if(jump(nums,next,nums[next])==true)
 18               return true;
 19            maxjump--;
 20         }
 21         return false;
 22     }
 23 }
View Code
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值