【LeetCode】Jump Game & Jump Game II

来源:互联网 发布:最游记一键淘宝端 编辑:程序博客网 时间:2024/04/30 12:53

参考链接

http://blog.csdn.net/pickless/article/details/9855891
http://www.cnblogs.com/tgkx1054/archive/2013/05/23/3095115.html

http://www.cnblogs.com/xinsheng/p/3510504.html

题目描述

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 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.)




题目分析

Jump Game
这是一个经典的贪心算法。
我们只关心,最远可以到达哪里。因为能够到达最远的地方了,那么最远之前的地方必然可以到达。
代码中的几个要点max = A[i] + i > max ? A[i] + i : max;如果从i点可以跳更远那么就更新最远点。
i <= max 这个条件必须满足,否则i都到达不了,后面的就更没办法到达了。


Jump Game
class Solution {public:    bool canJump(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int max = 0;        for (int i = 0; i < n && i <= max; i++) {            max = A[i] + i > max ? A[i] + i : max;        }        return max >= n - 1;    }};
Jump Game II

思路:
声明一个数step[n],step[i]表示到i所用的最小步数。
class Solution { public:     int jump(int A[], int n)      {         int *step=new int[n];        memset(step,0,sizeof(step));        int lasti=0,maxreach=A[0],reachindex;          for(int i=1;i<n;i++)         {            if(lasti+A[lasti]>=i)           {              step[i]=step[lasti]+1;           }           else           {               step[i]=step[reachindex]+1;               lasti=reachindex;           }           if(i+A[i]>maxreach)            {               maxreach=i+A[i];               reachindex=i;                        }         }         return step[n-1];            } }; 


分析:
假设第i步可以跳的范围是start,end
那第i+1步能跳进的范围是end+1到(从start到end所能跳跃的最远距离)
这样每一步都用贪心算法,可以得出最小步数。

class Solution {public:    int jump(int A[], int n) {        if(n <= 1)            return 0;         int start = 0, end = 0;        int cnt = 0;        while(end < n-1) {            int maxdis = 0;            for(int i = start; i <= end; i ++) {                maxdis = max(maxdis, A[i]+i);            }            start = end+1;            end = maxdis;            cnt ++;        }        return cnt;    }};




推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/
vector使用方法
http://www.cplusplus.com/reference/vector/vector/

0 0
原创粉丝点击