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