提目描述
N阶楼梯上楼问题:一次可以走两阶或一阶,问有多少种上楼方式。(要求采用非递归)
输入描述
输入包括一个整数N,(1<=N<90)。
输出描述
可能有多组测试数据,对于每组数据,
输出当楼梯阶数是N时的上楼方式个数。
示例
输入
4
输出
5
原题地址
总结
(n-1)阶走一步,(n-2)阶走两步。
Code
递归方法
#include<iostream>
using namespace std;
//递归写法
int getCount(int n)
{
if (n == 1) return 1;
else if (n == 2) return 2;
else
{
return getCount(n - 1) + getCount(n - 2);//(n-1)阶走一步,(n-2)阶走两步
}
}
int main()
{
int n;
while (cin >> n)
{
int count = 0;
count = getCount(n);
cout << count;
}
return 0;
}
数学归纳法
#include <iostream>
using namespace std;
int main()
{
int a[91];
a[1] = 1;
a[2] = 2;
for (int i = 3; i < 91; i++)
a[i] = a[i - 1] + a[i - 2];
int n;
while (cin >> n)
cout << a[n];
}
压栈法
#include<iostream>
#include<stack>
using namespace std;
void getCount(int n)
{
if (n == 1 || n == 2)
cout << n;
else
{
stack<int> st;
st.push(1);
st.push(2);
int i = 2;
while (i!=n)
{
//基本思路还是,(n-1)阶走一步,(n-2)阶走两步
//不同的是,从底层开始压栈,到了n的时候,取栈顶元素
int temp2 = st.top();
st.pop();
int temp1 = st.top();
st.pop();
st.push(temp2);
st.push(temp2 + temp1);
i++;
}
cout << st.top();
}
}
int main()
{
int n;
while (cin >> n)
getCount(n);
return 0;
}