(剑指offer)跳台阶

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

时间限制:1秒 空间限制:32768K 热度指数:314942

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

思路
逆向思维,最后一级要么跳1级,要么跳2级。其实发现还是斐波那契数列的应用!

代码示范1:

public class Solution {
    public int JumpFloor(int target) {
        //关键:最后一次要么跳一级,要么跳2级
        if(target == 1){
            return 1;
        }else if(target == 2){
            return 2;
        }else{
            return JumpFloor(target-1) + JumpFloor(target-2);
        }
    }
}

代码示范2(优化了下):

public class Solution {
    public int JumpFloor(int target) {
        //关键:最后一次要么跳一级,要么跳2级
        int a = 0;
        int b = 0;
        int c = 1;
        for(int i = 1; i <=target; i++){
            a = b + c;
            b = c;
            c = a;
        }
        return a;
    }
}

猜你喜欢

转载自blog.csdn.net/ccnuacmhdu/article/details/84678938