码迷,mamicode.com
首页 > 其他好文 > 详细

55. Jump Game

时间:2019-02-08 13:07:39      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:rmi   can   max   position   min   一个   class   位置   always   

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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
就是数组位置是能跳得最远距离,然后问能不能从index 0 跳到最后一个index
好的, 回溯法上头了,看啥都是回溯法
然后只想了个大概,代码还是写不出来。参考一下答案
public class Solution {
    public boolean canJumpFromPosition(int position, int[] nums) {
        if (position == nums.length - 1) {
            return true;
        }

        int furthestJump = Math.min(position + nums[position], nums.length - 1);
        for (int nextPosition = position + 1; nextPosition <= furthestJump; nextPosition++) {
            if (canJumpFromPosition(nextPosition, nums)) {
                return true;
            }
        }

        return false;
    }

    public boolean canJump(int[] nums) {
        return canJumpFromPosition(0, nums);
    }
}

然而,无情的系统提示,time limit error

下面是牛逼哄哄的Greedy算法

class Solution {
    public boolean canJump(int[] nums) {
        int lastposition = nums.length-1;
        for(int i = nums.length - 1; i >= 0; i--){
            if(nums[i]+i >= lastposition){
                lastposition = i;
            }
        }
        return lastposition==0;
    }
}

真尼玛巧夺天工

55. Jump Game

标签:rmi   can   max   position   min   一个   class   位置   always   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10355826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!