一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:
可归纳为斐波那契数列问题。
1个台阶—-1种;
2个台阶—-2种;
3个台阶—-3种;
4个台阶—-5种;
.
.
.
.
.
.
n个台阶( n>2 ),可以看作是跳(n-1)个台阶的次数加1个台阶的次数;
代码:
/**
* Created by JT on 2017/3/12.
*/
public class Solution {
public int Fib(int n){
if(n == 0)
return 0;
else if(n == 1)
return 1;
else if(n == 2)
return 2;
else
return Fib(n-1)+Fib(n-2);
}
public int JumpFloor(int target) {
return Fib(target);
}
public static void main(String[] args){
int n = 30;
Solution s = new Solution();
for(int i=0; i<n; i++)
System.out.println(s.JumpFloor(i));
}
}
变态跳台阶:
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
n=1—-1种;
n=2—-2种;
n=3—-4种;
n=4—-8种;
n=5—-16种;
.
.
.
.
.
.
n个台阶—-2^(n-1)种。
public class Solution {
public int JumpFloorII(int target) {
return (int)Math.pow(2, target-1);
}
}