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.)
このタイプのテーマは、まずダイナミックな計画法、二分法などを使うのではなく、まずゲームのルールを明らかにしなければならない.
問題の意味がまだそんなにはっきりしていないような気がしますが、まず3つの質問に答える必要があります.
1任意の位置から数を取ることができますか?
2重複数を利用できますか?
3 1つの数を取るごとにジャンプする必要がありますか?
回答:
1いいえ、現在位置の数しか取れません
2いいえ
3いいえ、ジャンプを超えなければいいです.例えば、現在の数が10であれば、0から10歩ジャンプすることができます.もちろん、私たちは0歩ジャンプしません.
次の2つのアルゴリズムは簡潔です.
最初のプログラム:
このプログラムは理解しやすい.
	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;
	}