カエルジャンプ階段2

問題の説明:カエルは一度に1ステップまでジャンプしたり、2レベルまでジャンプしたりできます。また、一度nレベルまでジャンプすることもできます。nレベルのステップにジャンプする方法をカエルに尋ねます。

アイデア:の最初のステップジャンプiはレベルの、そこに残りFN- - I)種は方法、基準ジャンプカエルジャンプ一歩、その結果FN-)= FN - - + ... + 1)FN-を - N-)、ここで、F(0)= 0、F(1)= 1、。。F(2)= 2、及びFN - - 1)= FN - - 1 - 1)+···+ FN- - 1-(n -1))、つまりfn)= 2 fn-1)。それは
f 0 = 0 f 1 = 1 f 2 = 2 f = f 1 + . . . . . . + f ( n n ) = 2 f ( n 1 ) f(0)= 0 \\ f(1)= 1 \\ f(2)= 2 \\ f(n)= f(n-1)+ ...... + f(nn)= 2f( n-1)

コード:

package hgy.java.arithmetic;

import org.junit.Test;

public class JumpFloorII {
	//根据思路代码实现
	public int jumpFloor(int target) {
		if (target <= 2)
			return target;
		else
			return 2 * jumpFloor(target - 1);
	}

	// 根据上述代码优化
	public int jumpFloor1(int target) {
		return target > 0 ? 1 << (target - 1) : 0;
	}

	// 模拟动作使用迭代的方法
	public int jumpFloor2(int target) {
		if (target <= 2)
			return target;
		int[] ways = new int[target + 1];
		ways[1] = 1;
		ways[2] = 2;
		for (int i = 3; i <= target; i++) {
			for (int j = 1; j < i; j++)//两步以上跳到终点跳法种数
				ways[i] = ways[i] + ways[j];
			ways[i]++;// 加一步直接跳到终点
		}
		return ways[target];
	}

	@Test
	public void test() {
		System.out.println(jumpFloor(6));
		System.out.println(jumpFloor1(6));
		System.out.println(jumpFloor2(6));
	}

}

元の記事を公開9件 ・いい ね0件 訪問35件

おすすめ

転載: blog.csdn.net/qq_35419705/article/details/105695503