爬楼梯

来源:互联网 发布:pc蛋蛋单双算法 编辑:程序博客网 时间:2024/04/30 14:05

有一段楼梯台阶共有15级,小明一步最多只能跨3级,请问小明登上这段台阶有多少种不同走法?

#include<iostream>#include<string.h>using namespace std;int f(int n) {int a=0;if(n==1)return 1;if(n==2)return 2;if(n==3)return 4;return a=f(n-1)+f(n-2)+f(n-3);return a;}int main() {int n;cin>>n;cout<<f(n);return 0;}

最终输出结果:5768.

裴波那契思想,1个台阶1种走法,2个台阶有2种走法(2,1+1),3个台阶4种走法(3,1+2,2+1,1+1+1),所以n个台阶有f(n-1)+f(n-2)+f(n-3).

原创粉丝点击