题目描述:
有一座高度是10级台阶的楼梯,从下往上走,每跨一步只能向上1级或者2级台阶。要求用程序求出一共有多少种走法。
思想:
使用动态规划易得:
F(10)=F(9)+F(8)
F(n)=F(n-1)+F(n-2)
因此比较斐波那契数列可得代码结构:
#include<iostream>
using namespace std;
int stair2(int i, int n, int x, int y)
{
if (i <= n)
stair2(i + 1, n, y, x + y);
else
return y;
}
int stair1(int n)
{
if (n == 1)
{
return 1;
}
else if (n == 2)
{
return 2;
}
else
{
return stair2(3, n, 1, 2);
}
}
int main()
{
int n;
cout << "请输入台阶数:";
cin >> n;
cout <<endl<< "共有" << stair1(n) << "种走法" << endl;
}
这个是改进版的斐波那契数列,保存中间过程,大大降低时间复杂度。当然,你也可以使用递归版的斐波那契数列代码。