[LeetCode]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.

这次挑了一道游戏性质的题来做,看到这道题首先想到的就是枚举,像这种形式明显会想到递归,于是就写了个递归的代码。

(突然想到有个遍历字符串的题,有空做一下)

#include <iostream>

class Solution {
public:
	bool canJump(int A[], int n) {
		int index = 0;
		if (jump(A, n, 0))
			return true;
		else
			return false;
	}
	bool jump(int A[], int n, int index)
	{
		if (index >= n - 1)
			return true;
		for (int i = 1; i <= A[index]; i++)
		{
			if (jump(A, n, index + i))
				return true;
		}
		return false;
	}
};

int main()
{
	Solution sl;
	int A1[5] = { 2, 3, 1, 1, 4 };
	int A2[5] = {3, 2, 1, 0, 4};
	std::cout <<sl.canJump(A1, 5) << std::endl;
	std::cout << sl.canJump(A2, 5) << std::endl;

	system("PAUSE");
	return 0;
}

代码看起来是对的,提交到OJ以后出现了Time Limit Exceeded,然后给出了这时的测试用例

Last executed input: [2,0,6,9,8,4,5,0,8,9,1,2,9,6,8,8,0,6,3,1,2,2,1,2,6,5,3,1,2,2,6,4,2,4,3,0,0,0,3,8,2,4,0,1,2,0,1,4,6,5,8,0,7,9,3,4,6,6,5,8,9,3,4,3,7,0,4,9,0,9,8,4,3,0,7,7,1,9,1,9,4,9,0,1,9,5,7,7,1,5,8,2,8,2,6,8,2,2,7,5,1,7,9,6]

这个看起来不能用递归了,得找另一种方法。

OK,另一种方法来了,其实这个问题可以是检查末尾点是否可以到达的问题,那么我们可以先检查[0, n-2]点中是否有点可以直接到达n-1,如果不是点0,那么检查这些能到达n-1的是否可以到达,如点k是否可以到达就检查[0, k-1]是否存在点可以到达。依然是递归方式:

class Solution {
public:
	bool canJump(int A[], int n) {
		if (CheckPointPossible(A, n - 1))
			return true;
		else
			return false;
	}
	//检查此点是否可以到达
	bool CheckPointPossible(int A[], int index)
	{
		if (index == 0)
		{
			return true;
		}
		for (int i = 0; i <= index - 1; i++)
		{
			if (A[i] >= index - i)
			{
				if (CheckPointPossible(A, i))
					return true;
			}
		}
		return false;
	}
};

居然又是 Time Limit Exceeded,好吧,看来这些点能节省的时间有限,得换种方法。


刚才看了一下discussion,有个comment里面的方法实在是醍醐灌顶啊!最近真的是得充值智商了,那么明显的方法搞得那么复杂。

我们只需要从0开始记录这个点能到达的最远点即i+A[i],当然,如果i+A[i]>=n-1了,自然就OK了,否则就在这段能到达距离内再次寻找,不断更新能到达的最远距离。

代码非常简洁明了!感谢discussion里的Mike


class Solution{
public:
	bool canJump(int A[], int n) {
		int canreach = 0;
		for (int i = 0; i < n - 1 && i <= canreach; i++)
		{
			if (i + A[i] >= n - 1)
				return true;
			if (i + A[i] > canreach)
				canreach = i + A[i];
		}
		return (canreach >= n - 1);
	}
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值