Frog jumping stairs 2

Problem description: A frog can jump up to 1 step at a time, or jump up to 2 levels ... It can also jump up to n levels at a time. Ask the frog how many ways to jump on an n -level step.

Ideas: The first step Jump to i -level, remaining there F ( n- - i ) species jump method, reference frog jump one step , so that F ( n- ) = F ( n- - 1) + ... + F ( n- - n- ), where F (0) = 0, F (. 1) =. 1, F (2) = 2, and F ( n- -. 1) = F ( n- -. 1 -. 1) + ????? + F ( n- - 1-( n -1)), so f ( n ) = 2 f ( n- 1). which is
f ( 0 ) = 0 f ( 1 ) = 1 f ( 2 ) = 2 f ( n ) = f ( n 1 ) + . . . . . . + f ( n n ) = 2 f ( n 1 ) f(0)=0\\f(1)=1\\f(2)=2\\f(n)=f(n-1)+......+f(n-n)=2f(n - 1)

Code:

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));
	}

}

Published 9 original articles · liked 0 · visits 35

Guess you like

Origin blog.csdn.net/qq_35419705/article/details/105695503