CCF NOI1072. 爬楼梯 (C++)

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/84998368

1072. 爬楼梯

题目描述

树老师爬楼梯,他可以每次走1级或者2级,输入楼梯的级数,求不同的走法数。例如:
楼梯一共有3级,他可以每次都走一级,或者第一次走一级,第二次走两级,也可以第一次走两级,第二次走一级,一共3种方法。

输入

输入包含若干行,每行包含一个正整数N(1<=N<=30),代表楼梯级数。

输出

不同的走法数,每一行输入对应一行输出。

样例输入

5
8
10

样例输出

8
34
89

数据范围限制

1<=N<=30

C++代码

#include <iostream>
#include <sstream>
#include <cassert>    // assert()

using namespace std;

const int max_N = 30;
int numOfWays;

void climbStairs(int sum, int num);
int GetInt(string strText);

int main()
{
    int N;
    string strText;

    while(1)
    {       
        getline(cin, strText);

        if (strText.size() == 0)
        {
            break;
        }
        else
        {
            N = GetInt(strText);

            assert(N>=1 && N<=max_N);
        
            numOfWays = 0;
        
            // use recursive method to find all ways to climb stairs
            climbStairs(N, 1);

            cout << numOfWays << endl;
        }
    }

    return 0;
}

void climbStairs(int sum, int num)
{
    if(0 == sum)
    {
        numOfWays++;
        return ;
    }
    for(int i=1; i<=sum; i++)
    {
        if(i >= 1 && i <= 2)  // one or two steps
        {
            climbStairs(sum-i, num+1);
        }
    }
}

int GetInt(string strText)
{
    int n = 0;
    stringstream os;

    os << strText;
    os >> n;

    return n;
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/84998368