剑指Offer--青蛙跳台阶引发的一系列问题

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
解法一(效率最高)
数学归纳法:
public class Solution {
    public int JumpFloor(int target) {
        if(target == 1 || target == 2) {
            return target;
        }
        int s1 = 1,s2 = 2,s3 = 0;
        for (int i = 3; i <= target; i++) {
            s3 = s1 + s2;
            s1 = s2;
            s2 = s3;
        }
        return s3;
    }
}

 解法二:递归解法(耗时)

public class Solution {
    public int JumpFloor(int target) {
        if(target == 1 || target == 2) {
            return target;
        } else {
            return JumpFloor(target - 1) + JumpFloor(target - 2);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/code4her/p/9508163.html