55. Jump Game

贪心算法

Jump Game 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.
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 Game II

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 is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

解析

使用贪心算法, 记录每一个i处的能达到的最大位置maxindex, 如果该maxindex大于等于n-1,证明可以到达该位置处,直接返回即可,每次更新该处的值maxindex值

maxindex =max(maxindex, i+nums[i])

用greedy来解,记录一个当前能达到的最远距离maxIndex:

  1. 能跳到位置i的条件:i<=maxIndex。
  2. 一旦跳到i,则maxIndex = max(maxIndex, i+A[i])。
  3. 能跳到最后一个位置n-1的条件是:maxIndex >= n-1
class Solution {
public:
    bool canJump(int A[], int n) {
        int maxIndex = 0;
        for(int i=0; i<n; i++) {
            if(i>maxIndex || maxIndex>=(n-1)) break;
            maxIndex = max(maxIndex, i+A[i]);
        } 
        return maxIndex>=(n-1) ? true : false;
    }
};

动态规划

维护一个一位数组dp,其中dp[i]表示达到i位置时剩余的步数,那么难点就是推导状态转移方程啦。我们想啊,到达当前位置的剩余步数跟什么有关呢,其实是跟上一个位置的剩余步数和上一个位置的跳力有关,这里的跳力就是原数组中每个位置的数字,因为其代表了以当前位置为起点能到达的最远位置。而下一个位置的剩余步数(dp值)就等于当前的这个较大值减去1,因为需要花一个跳力到达下一个位置,所以我们就有状态转移方程了:dp[i] = max(dp[i - 1], nums[i - 1]) - 1,如果当某一个时刻dp数组的值为负了,说明无法抵达当前位置,则直接返回false,最后我们判断dp数组最后一位是否为非负数即可知道是否能抵达该位置

class Solution {
    public boolean canJump(int[] nums) {
        if(nums==null || nums.length==0) return false;
        int n = nums.length;
        if(n==1) return true;
        //能最终达到的下标位置信息
        int [] result = new int[n];
        //第一个位置的信息情况
       // result[0] = nums[0]-1;
        for(int i=1;i<n;i++){
            result[i] = Math.max(result[i-1],nums[i-1])-1;
            if(result[i]<0) return false;
        }
        return result[n-1]>=0;
    }
}

45. Jump Game II

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值