0
点赞
收藏
分享

微信扫一扫

跳跃游戏(优化

那小那小 2022-03-15 阅读 85

给你一个非负整数数组 nums ,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

假设你总是可以到达数组的最后一个位置。

在这里插入图片描述
思路:找能走到最远的一步。`

class Solution {
    public int jump(int[] nums) {
        if(nums.length==1) return 0;
        return jump1(nums,0);
    }
    public int jump1(int[] nums,int start){
        int temp1=-1001;
        int flag=0;
        if(start>=nums.length) return 1;
        if(nums[start]==0) return 1001;
        if(nums[start]+1+start>=nums.length){
            return 1;
        }else{
            for(int i=1;i<=nums[start];i++){
                if(i+nums[start+i]-1>temp1) {
                    flag=start+i;
                    temp1=i+nums[start+i]-1;
                }
            }
            return 1+jump1(nums,flag);
        }
    }
}
举报

相关推荐

跳跃游戏

跳跃游戏 II

跳跃游戏IV

跳跃游戏2

【leetcode】 跳跃游戏 IV

算法分析:跳跃游戏

0 条评论