1. 程式人生 > >LeetCode Jump Game II 前跳遊戲II

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 is2. (Jump1step from index 0 to 1, then3steps 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;
	}
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;
	}