Leetcode 55. Jump Game
来源:互联网 发布:js登录功能 编辑:程序博客网 时间:2024/04/27 18:06
题目
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]
, returntrue
.
解释:
初始位置在A[0],最大能跳动2步,假定跳动最大步数,此时到了A[2] = 1,往前只能跳动一步,
所以到了A[3] = 1,所以正好再向前跳动一步,到达最后一个索引,所以返回为 true。
A = [3,2,1,0,4]
, returnfalse
解释:
- 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 }
阅读全文
1 0
- [LeetCode]55.Jump Game
- LeetCode 55.Jump Game
- LeetCode --- 55. Jump Game
- [Leetcode] 55. Jump Game
- [leetcode] 55.Jump Game
- [leetcode] 55.Jump Game
- *LeetCode 55. Jump Game
- LeetCode 55. Jump Game
- [leetcode] 55. Jump Game
- leetcode 55. Jump Game
- 55. Jump Game LeetCode
- 【LeetCode】55. Jump Game
- leetcode 55. Jump Game
- [LeetCode] 55. Jump Game
- LeetCode 55. Jump Game
- LeetCode *** 55. Jump Game
- Leetcode 55. Jump Game
- LeetCode-55.Jump Game
- 容易忘的Java基础点
- Mangos Zero服务器搭建简要过程及常见问题
- 倍福PLC与MCGS通讯连接
- phpstudy中一设置虚拟域名apach就停止的解决办法及非80端口设置虚拟域名
- 身体报废
- Leetcode 55. Jump Game
- 小程序富文本编辑器的问题
- hdu6143 Killer Names(strling数)
- 冒泡排序详解
- C#6.0&VISUALSTUDIO 2015 C#入门经典 第7版pdf
- netty实现websocket
- 第十五天
- 神经网络的预训练
- jsp中name和id