跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)

解法一:(下台阶)

1
2
3
4
5
6
7
8
9
10
11
12
13
public class  {

public int JumpFloor(int target) {
if(target<=0)
return 0;
if(target==1)
return 1; //1级台阶只有1种跳法:1(向下递归终止条件1,开始向上返回递归)
if(target==2)
return 2; //2级台阶有2种跳法:1,2(向下递归终止条件2,开始向上返回递归)
else // target>=3
return JumpFloor(target-2)+JumpFloor(target-1); //从上往下计算,即“下台阶”
}
}

解法二:

规律:JumpFloor(target)= JumpFloor(target-2)+JumpFloor(target-1))

可得数列JumpFloor(1)、JumpFloor(2)、… JumpFloor(n) 为“斐波那契数列”(0除外)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class  {

public int JumpFloor(int target) {
if(target<=0)
return 0;
if(target==1)
return 1; //1级台阶只有1种跳法:1(向下递归终止条件1,开始向上返回递归)
if(target==2)
return 2; //2级台阶有2种跳法:1,2(向下递归终止条件2,开始向上返回递归)
else {//target>=3
int j1=1,j2=2;
int j3=0;
while(target>=3){ //当做斐波那契数列处理,从第3项开始
j3 = j1 + j2;
j1 = j2;
j2 = j3;
target--;
}
return j3;
}
}
}