【算法刷题】leetcode 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], returntrue.

A =[3,2,1,0,4], returnfalse.


利用贪心

    bool canJump(int A[], int n) {
        if(A==nullptr)
            return false;
        int maxnum = A[0];
        for(int i=1;i

进阶版    到达最后一个最少的步数

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A =[2,3,1,1,4]

The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.)


首先  利用了动态规划,dp[i]表示到达当前位置最小的步数,代码如下

    int jump(int A[], int n) {
        if(A==nullptr)
            return 0;
        int* dp = new int[n];
        dp[0]=0;
        for(int i=1;i

在牛客网上没有提示超时,过了,但是在网上看到说在leetcode上利用动态规划会超时,最好的方法还是利用贪心:


cur是当前能到达的最远位置,即最远能覆盖的位置,last是上一步能到达的最远位置,遍历数组,用i + nums[i]更新cur,然后判断如果当前位置超过了last,即上一步能到达的最远位置,说明需要再跳一次了,并更新last

    int jump(int A[], int n) {
        if(A==nullptr)
            return 0;
        int res(0),last(0),cur(0);
        for(int i=0;ilast)
            {
                ++res;
                last = cur;
            }
            cur=max(cur,i+A[i]);
        }
        
        
        return res;
    }

你可能感兴趣的:(算法题)