Leetcode 55. Jump Game dp

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

题目链接:https://leetcode.com/problems/jump-game/

这题真的废了好多脑子,des作为目标点,如果 i+nums[i]>=des,那么目的地变化 des=i, 前面的节点可以跳到des=i,就成功了 

大家也可以去看这题的加强版leetcode 45. Jump Game II贪心算法

class Solution {
public:
    bool canJump(vector<int>& nums) {
       int dp[nums.size()]={0};
       memset(dp,0,sizeof(dp));
       int len=nums.size();
        int des=len-1;
        dp[len-1]=1;//防止仅有一个元素的例子
       for(int i=len-2;i>=0;i--)
       {
           if(i+nums[i]>=des)
           {
               dp[i]=1;
               des=i;
           }
       }
        return dp[0]==1;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86525806