剑指offer[跳台阶]

剑指offer[跳台阶]

题目描述

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

思路

设F(n)为第n级台阶的跳法,则当青蛙站在有n层台阶前时,它只能跳一级或者两级。当他跳一级后,台阶的可能跳法变为F(n-1)。当他跳两级后,台阶的可能跳法变为F(n-2)。所以F(n)=F(n-1)+F(n-2)。此为斐波那契数列的递推公式!!!

代码

public class Solution {
    public int JumpFloor(int target) {
        int result=0;
        int first=1;
        int second=2;
        if(target<1){
            return 0;
        }else if(target<3){
            return target;
        }else{
            for(int i=3;i<=target;i++){
                result=second+first;
                first=second;
                second=result;
            }
        }
        return result;
    }
}

细节知识

斐波那契数列

猜你喜欢

转载自blog.csdn.net/qq_42404593/article/details/84394935
今日推荐