题目描述

有10个台阶,你可以走1步,2 步或者3步,问一共有几种走法

问题分析

细细想想,如果用f(n)表示那个台阶的走法数,那么f(n) = f(n - 1) + f(n - 2) + f(n - 3),而f(0) = 1, f(1) = 1, f(2) = 2。至于实现,可以用递归,也可以循环实现。

其实,这也是求树的叶子节点的问题。

附上一段代码

#include <stdio.h>
#include <iostream>
using namespace std;
#define N 100
int fun(int n)
{
    //initialzing
    int f[N] = {1, 1, 2};
    for (int i = 3; i <= n; i++)
        //core code
        f[i] = f[i - 1] + f[i - 2] + f[i - 3];
    return f[n];
}
int main()
{
    int n, result;
    while(scanf("%d", &n) != EOF)
    {
        result = fun(n);
        printf("result = %d\n", result);
    }
    system("pause");
    return 0;
}

 

相关文章:

  • 2021-11-30
  • 2021-12-03
  • 2021-11-29
  • 2021-12-12
  • 2022-01-09
  • 2022-12-23
  • 2021-12-16
  • 2022-12-23
猜你喜欢
  • 2021-10-29
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
相关资源
相似解决方案