华中科技大学复试 N阶楼梯上楼问题

提目描述

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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值