您的位置:首页 > 房产 > 建筑 > 河源网站建设_网络文化经营许可证流程_郴州网站建设_百度网盘电脑版官网

河源网站建设_网络文化经营许可证流程_郴州网站建设_百度网盘电脑版官网

2025/3/5 5:52:10 来源:https://blog.csdn.net/2301_81236660/article/details/145963603  浏览:    关键词:河源网站建设_网络文化经营许可证流程_郴州网站建设_百度网盘电脑版官网
河源网站建设_网络文化经营许可证流程_郴州网站建设_百度网盘电脑版官网

贪心算法

  • 跳跃游戏
  • 跳跃游戏2

在这里插入图片描述
在这里插入图片描述

跳跃游戏

题目在这里插入图片描述
拿到题目就暴力穷举,我用的是dfs,加上备忘录之后还是超出时间限制。就考虑一下贪心算法。你想 我在[0,n-2]位置遍历求出可以跳跃的最远距离,用farthest更新最大值,如果>=终点就返回true。

DFS递归:时间复杂度最坏是O(N*N)
在这里插入图片描述

class Solution {//dfsint[]memo;public boolean canJump(int[] nums) {memo=new int[nums.length];//memo[i]我在下标i出能不能到达终点 能1 不能0 没有访问-1Arrays.fill(memo,-1);//我站在下标为0的位置 求能不能跳到终点return dfs(nums,0);}//定义:从startIndex为起点,返回能不能到达终点boolean dfs(int[]nums,int startIndex){//到了终点 返回trueif(startIndex==nums.length-1){return true;}//startIndex曾经访问过,不再重复访问if(memo[startIndex]!=-1){return memo[startIndex]==1;}int steps=nums[startIndex];//可以跳跃几步for(int i=1;i<=steps;i++){//跳跃i步 看看我在下标startIndex+i位置可不可以到达终点if(dfs(nums,startIndex+i)==true){memo[startIndex+i]=1;return true;}}return false;}
}

贪心:时间复杂度O(N)

class Solution {public boolean canJump(int[] nums) {int n=nums.length;int farthest=0;for(int i=0;i<n-1;i++){//不断更新最远index 在i位置的最远距离是i+nums[i]farthest=Math.max(farthest,i+nums[i]);if(farthest<=i){return false;}}return farthest>=n-1;}
}

跳跃游戏2

题目在这里插入图片描述

class Solution {//dfs 暴力穷举final int bigVal=100000;int[] memo;public int jump(int[] nums) {int sz=nums.length;memo=new int[sz];//memo[i]:记录在下标为i处到达终点的最小步数Arrays.fill(memo,-1);return dfs(nums,0);}//定义:以startIndex为起点,返回到达终点的最小跳跃次数int dfs(int[]nums,int startIndex){//起点就是终点 跳跃0步if(startIndex==nums.length-1){return 0;}//曾经访问过if(memo[startIndex]!=-1){return memo[startIndex];}//不可跳跃if(nums[startIndex]==0){return bigVal;}int minStep=bigVal;int steps=nums[startIndex];//从startIndex可以跳steps步for(int i=1;i<=steps;i++){//找出最小的跳跃次数if(startIndex+i<nums.length){memo[startIndex+i]=dfs(nums,startIndex+i);minStep=Math.min(minStep,memo[startIndex+i]+1);}}return minStep;}
}

贪心:O(N)

class Solution {//贪心 public int jump(int[] nums) {int farthest=0,end=0,jump=0;int sz=nums.length;for(int i=0;i<sz-1;i++){farthest=Math.max(farthest,nums[i]+i);//可以跳到[i+1,farthest]之间,if(i==end){jump++;end=farthest;}}return jump;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com