剑指Offer——跳台阶、变态跳台阶(青蛙)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lollipop66/article/details/79780518

跳台阶:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
递归法(剑指offer解释的很明白):
public class Solution {
    public int JumpFloor(int target) {
        if(target==1)
            return 1;
        if(target ==2)
            return 2;
        if (target>2)
            return JumpFloor(target-1) + JumpFloor(target-2);
        return 0;
    }
}
非递归方式:
public class Solution {
    public int JumpFloor(int target) {
        if(target==1)
            return 1;
        if(target ==2)
            return 2;
        int one =1;
        int two = 2;
        int count=0;
        for(int i =3;i<target+1;i++){
            count = one + two;
            one = two;
            two = count;
        }
        return count;
    }
}
这里发现类似斐波那契数列,当前跳法的总数等于前一种总数与前前种法的总和:
例如:
target=1
1
target = 2
1 1, 2
target = 3
1 1 1,2 1,1 2
(这里可以看出target=3时,在target=2的后面加1,就是前二种跳法,在target后面加2,就是第三种跳法)
以此类推:
target = 4
1 1 1 1,2 1 1,1 2 1,(target=3,后面加1)1 1 2,2 2(target=2,后面加2)

变态跳台阶:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
public class Solution {
    public int JumpFloorII(int target) {
        if(target==0)
            return 0;
        int count=1;
        for(int i =0;i<target;i++){
            count = count+JumpFloorII(i);
        }
        return count;
    }
}
当前的跳法数等于前面所有种数和加1,这里也可以采用递推公式做等于2^(n-1)

猜你喜欢

转载自blog.csdn.net/Lollipop66/article/details/79780518
今日推荐