[LintCode] 跳跃游戏

来源:互联网 发布:二维动画软件 编辑:程序博客网 时间:2024/05/18 01:37

给出一个非负整数数组,你最初定位在数组的第一个位置。   
数组中的每个元素代表你在那个位置可以跳跃的最大长度。    
判断你是否能到达数组的最后一个位置。

注意事项
这个问题有两个方法,一个是贪心和 动态规划。
贪心方法时间复杂度为O(N)。
动态规划方法的时间复杂度为为O(n^2)。
我们手动设置小型数据集,使大家阔以通过测试的两种方式。这仅仅是为了让大家学会如何使用动态规划的方式解决此问题。如果您用动态规划的方式完成它,你可以尝试贪心法,以使其再次通过一次。

样例
A = [2,3,1,1,4],返回 true.
A = [3,2,1,0,4],返回 false.

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.

Notice
This problem have two method which is Greedy and Dynamic Programming.
The time complexity of Greedy method is O(n).
The time complexity of Dynamic Programming method is O(n^2).
We manually set the small data set to allow you pass the test in both ways. This is just to let you learn how to use this problem in dynamic programming ways. If you finish it in dynamic programming ways, you can try greedy method to make it accept again.

Example
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

public class Solution {    /**     * @param A: A list of integers     * @return: The boolean answer     */    public boolean canJump(int[] A) {        if(null == A || A.length == 0)return false;        int i = 0, max = 0;        while(i <= max) {            max = Math.max(max, i+A[i]);            if(max >= A.length - 1) {                return true;            }            i++;        }        return false;    }}
public class Solution {    /**     * @param A: A list of integers     * @return: The boolean answer     */    public boolean canJump(int[] A) {        if(null == A || A.length == 0)return false;        int i = 0, max = 0;        while(max < A.length - 1) {            max = Math.max(max, i+A[i]);            i++;            if(max < i) {                return false;            }        }        return true;    }}
public class Solution {    /**     * @param A: A list of integers     * @return: The boolean answer     */    public boolean canJump(int[] A) {        if(null == A || A.length == 0)return false;        if(A.length == 1) return true;        int max = 0;        for(int  i = 0; i < A.length - 1; i++) {            max = Math.max(max, i+A[i]);            if(max >= A.length - 1) {                return true;            }else if(max <= i){                return false;            }        }        return false;    }}
0 0
原创粉丝点击