数据结构算法每日一练(三)青蛙跳台阶

2021/9/21 11:56:51

本文主要是介绍数据结构算法每日一练(三)青蛙跳台阶,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数据结构算法每日一练(三)青蛙跳台阶

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

(1)请用递归的方式求 n 级的台阶总共有多少种跳法: int jumpFloor(int n);

(2)给出此递归函数的时间复杂度。

解析:

当n = 0, jumpFloor(0) = 0;

当n = 1, jumpFloor(1) = 1;

当n = 2, jumpFloor(2) = 2;

当n > 3, jumpFloor(n) = jumpFloor(n - 1) + jumpFloor(n - 2);

#include <iostream>
using namespace std;
int jumpFloor(int n) {
    if (n < 3)
        return n;
    else
        return jumpFloor(n - 1) + jumpFloor(n - 2);
}
int main() {
    int n;
    cin >> n;
    int res = jumpFloor(n);
    cout << res << endl;
    return 0;
}

时间复杂度为递归调用 O ( 2 n ) O(2^n) O(2n)

该题为斐波那契数列,分析方法与其一致。数据结构算法每日一练(一)斐波那契数列

斐波那契数列递推公式 a n = 1 5 [ ( 1 + 5 2 ) n − ( 1 − 5 2 ) n ] a_n=\frac{1}{\sqrt{5}}[(\frac{1+\sqrt{5}}{2})^n - (\frac{1-\sqrt{5}}{2})^n] an​=5 ​1​[(21+5 ​​)n−(21−5 ​​)n]



这篇关于数据结构算法每日一练(三)青蛙跳台阶的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程