LeetCode- Jump game

来源:互联网 发布:淘宝的卡券包在哪里 编辑:程序博客网 时间:2024/06/05 14:42

    • jump game I
      • 题目描述
      • 思路阐述
        • 贪心
        • 动态规划
      • 代码
      • 下一篇

jump game I

1 . 题目描述

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[0]可以跳到A[1]A[2],跳到A[2],最多跳1步,到A[3],最多跳一步,到A[4],最多跳一步,到A[5].true
A[0]到A[3],A[3]去不了。第二个例子false。


思路阐述

1. 贪心

依次遍历数组,求每一步所能达到的最远位置的最大值
1. 这个最大值如果大于或等于n - 1,则表示一定能达到最后一个位置。
2. 而如果在遍历过程中,发现某个位置(数组下标)大于最远位置了,那也就是说不可能到达这个位置,当然就不可能到达最后了;

比如样例中第二个例子:
1. 扫描到3,far = 0 + 3
2. 扫描到2,far = max(3, 1 + 2) = 3
3. 扫描到1,far = max(3, 2 + 1) = 3
4. 扫描到0,far = max(3, 3 + 0) = 3
5. 扫描到4,此时,数组下标为4,4 > 3,失败


2. 动态规划

设状态为 f[i],表示从第 0 层出发,走到 A[i] 时剩余的最大步数,则状态转移方程为:f[i] = max(f[i − 1], A[i − 1]) − 1, i > 0代码 1// LeetCode, Jump Game// 思路 1,时间复杂度 O(n),空间复杂度 O(1)


依次遍历数组,设maxJump为当前最远能跳到的距离。
1. 如果i+maxJump>=n-1说明true
2. 若maxJump=0说明没办法跳了,为false.
3. 每走一步,即i++时,maxJump-=1。


代码

代码一(对应贪心算法)

class Solution{    public:        bool canJump(int A[], int n) {            int max = 0;            for(int i = 0; i < n; i++) {                if(i > max) return false;                int nowMax = i + A[i];                if(nowMax > max) max = nowMax;            }            return true;        }};

代码二(动态规划)

class Solution {public:    bool canJump(int A[], int n) {        if (n == 1) return true;        int maxJump =0;//current you can jump        for (int i = 0; i < n; i++){            maxJump--;            if (maxJump < A[i])                maxJump = A[i];            if (!maxJump)                return false;            if (maxJump + i >= n - 1 )                return true;        }        return false;    }};

4. 下一篇

下一篇是jump game II 参见我的博客列表。

原创粉丝点击