Jump_Game

题目描述: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低时间复杂度版


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值