层次遍历、递归:jump-game
来源:互联网 发布:网络语雪崩是什么意思 编辑:程序博客网 时间:2024/05/26 12:02
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], returntrue.
A =[3,2,1,0,4], returnfalse.
析:每次从某位置可以左右跳,跳的步数<=A[i]
法1:贪心法,略,参考网友的
法2:类似层次遍历求法。
比如第一次只有末尾的下标7,下次判断能从7传到的下标为3、5,下次再从下标3、5再传递一个层次,最后判断0是否在不满足的集合中。
public boolean canJump(int[] A) { if(A.length==0 || A.length==1) return true; // 放的是下标 Set<Integer> oldSet = new HashSet<>(); Set<Integer> newSet = new HashSet<>(); // 不能跳到末尾的点 Set<Integer> noOldSet = new HashSet<>(); Set<Integer> noNewSet = new HashSet<>(); newSet.add(A.length-1); for(int i=0;i<A.length-1;i++) noNewSet.add(i); while(newSet.size()!=0){ oldSet.clear(); oldSet.addAll(newSet); newSet.clear(); noOldSet.clear(); noOldSet.addAll(noNewSet); for(int no:noOldSet) for(int y:oldSet){ // 距离<=最大步数 if(Math.abs(no-y)<=A[no]){ noNewSet.remove(no); newSet.add(no); // 出现了下标0 if(no==0) return true; } } } return false; }
法3:用递归写,注意为了递归停止,必须用集合保存已经访问过的位置
import java.util.*;public class Main { public static void main(String[] args){ Scanner sc= new Scanner(System.in); Main main = new Main(); int[] A1= {2,3,1,1,4}; int[] A2={1,1,0,1}; System.out.println(main.canJump(A1)); System.out.println(main.canJump(A2)); } public boolean canJump(int[] A) { if(A.length==0 || A.length==1) return true; Set<Integer> set = new HashSet<>(); return canJump(A,0,set); } // set里放已经考虑过的位置,考虑过的就不用重复考虑了,用来栈的停止 public boolean canJump(int[] A,int startIndex,Set<Integer> set) { //Set<Integer> set = new HashSet<>(); if(startIndex>=A.length-1) return true; else if(startIndex<0) return false; else { if(!set.contains(startIndex)) { set.add(startIndex); if(A[startIndex]==0) return false; else { for(int step=1;step<=A[startIndex];step++){ if(canJump(A,startIndex+step,set) || canJump(A,startIndex-step,set)) return true; } return false; } } else { return false; } } }}
阅读全文
0 0
- 层次遍历、递归:jump-game
- 递归降序遍历层次目录
- 二叉树遍历(层次,递归,非递归)
- 二叉树(前中后序递归非递归遍历,层次遍历
- 二叉树的遍历(递归+非递归+层次遍历)
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- 朴素贝叶斯
- 【哈希查找】hashtable
- 前端开发必备软件/工具/学习网址
- 设计模式之原型模式
- 面试时遇到的一些题
- 层次遍历、递归:jump-game
- CCPC2017网络赛1005 CaoHaha's staff——找规律
- 安装Python 3.6 在Ubuntu 16.04 LTS 版本
- 2017.08.19【NOIP提高组】模拟赛B组总结
- ajax以get和post方式请求
- hbase的安装和启动
- css3放大显示div(由远及近显示)
- win10下移动硬盘位置不可用无法访问
- 皮克定理