55. Jump Game

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

===========

非负数组,数组元素表示在当前位置能jump的最大距离,

问:是否能到达最后的位置?

----------

思路:正向贪心的思路,

每一步记住能够到达最远的距离,就好。

=====

code

class Solution {
    //本题正向贪心
public:
    bool canJump(vector<int>& nums) {
        int maxLocation;//当前可能到达的最大位置(下标)
        maxLocation = nums[0];
        int length = nums.size();
        for(int i = 0;i<length && maxLocation>=i;i++){
          ///maxLocation>=i 在这里是剪枝,遇到1,2,0.0.0.0.0.0.0....这样直接返回,无需遍历整个数组了。 maxLocation
= max(maxLocation,i+nums[i]); } return maxLocation >= (length-1); } };

 2,也可以采用爬楼梯方法

思路:

@int max_left
bool canJump{
  max_left  = nums.size()-1;
  for(int i = nums.size()-2;i>=0;i--){
    if(nums[i]+i>=max_left) max_left = i;    
  }
  return max_left==0?
}

以上是关于55. Jump Game的主要内容,如果未能解决你的问题,请参考以下文章

55. 45. Jump Game II *HARD*

[leetcode][55] Jump Game

Leetcode55 Jump Game

Leetcode 55. Jump Game

55. Jump Game

55. Jump Game