1. 程式人生 > >Leetcode 55. Jump Game

Leetcode 55. Jump Game

[1] 非負數 貪心思想 for str 直接 例如 first closed

題目

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

Leetcode 55. Jump Game