LeetCode Jump Game II 前跳游戏II

Jump Game II 

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

这个类型的题目,先不要想去用什么动态规划法,二分法等等,而是先要搞清楚它的游戏规则。

感觉题意还是不是那么清楚,需要先回答三个问题:

1 是否可以从任意位置取数?

2 是否可以利用重复数?

3 每取一个数是否需要跳尽?

答:

1 不可以,只能取当前位置的数

2 不可以

3 不用,不超跳就行,比如当前数是10,那么可以跳0到10步,当然我们不会跳0步。

 下面两个算法都很简洁的。

第一个程序:

这个程序好理解点。

	int jump(int A[], int n) {
		if(n==1) return 0;//注意:别忘了特殊情况判断!
		int i = 0, last = 0, maxIndex = 0, step = 0;
		while (i+A[i] < n-1)//=n-1的时候就已经到达尾端了,所以不是n
		{
			for (maxIndex = i; last <= i+A[i]; last++)
				if (last+A[last] >= maxIndex+A[maxIndex]) maxIndex=last;
			step++;
			i = maxIndex;
		}
		return ++step;
	}

这个程序也很简洁,动动手就能理解了。
http://discuss.leetcode.com/questions/223/jump-game-ii

int jump2(int A[], int n) {
		int ret = 0;
		int last = 0;
		int curr = 0;
		for (int i = 0; i < n; ++i) {
			if (i > last) {
				last = curr;
				++ret;
			}
			curr = max(curr, i+A[i]);
		}

		return ret;
	}


 

 和上面的下标处理有一点点不一样。

//2014-1-27
	int jump(int A[], int n) 
	{
		int num = 0;
		int rec_pos = 0;
		int max_step = 0;

		for (int i = 0;rec_pos < n-1; i++)
		{
			if (A[i]+i > max_step) max_step = A[i]+i;
			if (i >= rec_pos)
			{
				rec_pos = max_step;
				num++;
				max_step = 0;
			}
		}
		return num;
	}

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值