字節跳動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;
}