字节跳动2020年九月笔试题-爬楼梯(不能连续爬两个两步)

字节跳动2020年九月笔试题-爬楼梯

我的CSDN-----------------------https://blog.csdn.net/qq_42093046/article/details/108434510

爬 n 层楼梯 每次只能爬一步或者两步,如果爬了一个两步则接下来不能爬两步,只能爬一步,求最多有多少种方法

笔试的时候感觉好复杂,后面自习思考之后,用状态转移(动态规划)+递归实现了

思路:f(n) = f(n-1)+f(n-2)

如果是f(n-2),说明爬了两步到达n层,则需要记录该状态,他的上一步只能是爬一步;

如果是f(n-1),说明爬了一步步到达n层,记录该状态,他的上一步可以是一步或者两步;

综上:

f(n, status) = f(n-1, 1)+f(n-2,2);

利用递归求值;

话不多说,上代码:

#include <iostream>
using namespace std;

long CountNumber(int n, int status)
{
    if (n < 1)
    {
        return 0;
    }
    if (n == 1)
    {
        return 1;
    }
    if (n == 2)
    {
        //上一步是走的两步, 则只能全走一步
        if (status == 2)
        {
            return 1;
        }
        //上一步是走的1步, 则可以全走一步,或者直接走两步
        if (status == 1)
        {
            return 2;
        }
    }

    
    if (n > 2)
    {
        if (status == 0)
        {
            return CountNumber(n - 1, 1) + CountNumber(n - 2, 2);   
        }
        if (status == 1)
        {
            return CountNumber(n - 1, 1) + CountNumber(n - 2, 2);
        }
        if (status == 2)
        {
            return CountNumber(n - 1, 1);
        }
    }
}

int main(int argc, char const *argv[])
{
    int n;
    cin >> n;
    long ret;

    ret = CountNumber(n, 0);
    cout << ret << endl;
    return 0;
}

posted @ 2020-09-06 18:00  Chilk  阅读(1318)  评论(2编辑  收藏  举报