数楼梯 递归代码

https://www.luogu.org/problemnew/show/P1255

这题用递推最好,但是当成递归可以用来练递归

思路,第i层可以由第i-1层走一步或者i-2层走两步过来(当然,i也可以由i-2走一步再走一步过来,可是这样和前面那个i-1层走一步上来有重复)

所以f(n)=f(n-1)+f(n-2)

再设置一下递归出口

if(n==1)return 1;
if(n==2)return 2; 就好了
#include<bits/stdc++.h>
using namespace std;
int f(int n)
{
    if(n==1)return 1;
    if(n==2)return 2;
    return f(n-1)+f(n-2);    
}
int main()
{
    std::ios::sync_with_stdio(false);
    int n;
    cin>>n;
    cout<<f(n)<<endl;
    
    
原文地址:https://www.cnblogs.com/zyacmer/p/10073947.html