Jump_Game

来源:互联网 发布:时尚芭莎 知乎 编辑:程序博客网 时间:2024/06/06 00:19
题目描述: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], return true.
                 A = [3,2,1,0,4], return false.
                译:给定一组非负整数,
                最初定位在数组的第一个索引处。
                数组中的每个元素表示该位置的最大跳转长度。

                判断是否能够到达最后一个索引。

解析:类似于树的搜索,以第一个索引为树的根节点,其可以到达的不为0的索引为其根节点,然后以这些子节点为根节点向下搜寻,直到得到结果。

public class Jump_Game {public static int array[];public static int couldcount=0;//mark即为数组下标public static int solve(int mark){//确定数组存在if(array.length>0){//递归的结束条件if(mark<array.length-1){//在判断条件时加上couldcount==0一旦出现可以到达的路就不再进行探索for(int i=mark;i<=mark+array[mark]&&couldcount==0;i++){//跳跃步数为零的点不考虑if(array[i]!=0){//System.out.println("mark="+mark+"时i="+i+"时i+array[i]="+(i+array[i]));//判断在这点能否直接到达最后的点if((i+array[i])>=(array.length-1)){couldcount++;//System.out.println(couldcount);}else{solve(i+1);}}//*******************************************************//else//{//System.out.println("mark="+mark+"时i="+i+"时array[i]为0");//}////*******************************************************}}}return couldcount;}public static void main(String[] args) {Scanner sc=new Scanner(System.in);//输入数组的长度int n=sc.nextInt();array=new int[n];for(int i=0;i<n;i++){array[i]=sc.nextInt();}if(solve(0)>0){System.out.println(true);}else{System.out.println(false);}//System.out.println(couldcount);}}


除此之外还有一个时间复杂度更低的代码:JumpGame低时间复杂度版


原创粉丝点击