微软算法面试(20):跳台阶问题

题目:一个台阶总共有n级,如果一次可以跳1级,也可以跳2级。

求总共有多少总跳法,并分析算法的时间复杂度。

分析:
采用递归思想,从第n个台阶开始研究,第 n 个台阶有两种跳法,一种是跳一级,还有 n -1级台阶要跳,另一种是跳两级,还有n -2级需要跳。
公式如下:
f(n) = f(n-1) + f(n-2),
其中 f(1) = 1, f(2) = 2。

实现如下:

#include<iostream>

using namespace std;

int findSteps(int n)
{
        if(n < 1) return 0;
        if(n == 1) return 1;
        if(n == 2) return 2;
        return findSteps(n-1) + findSteps(n-2);
}

int main()
{
        for( int i = 0; i < 10; i ++)
                cout << i << "step has num: " << findSteps(i) << endl;
        return 0;
}

输出结果为:
0step has num: 0

1step has num: 1

2step has num: 2

3step has num: 3

4step has num: 5

5step has num: 8

6step has num: 13

7step has num: 21

8step has num: 34

9step has num: 55

 

 
posted @ 2021-01-31 11:04  天涯学馆  阅读(102)  评论(0编辑  收藏  举报