问题描述:某楼梯共有N阶,一次可以跨一阶,也可以跨两阶,问总共有多少种走法~
采用递归的方法来完成。
总共走法 = 第一次跨一阶的走法 + 第一次跨两阶的走法
采用递归的方法来完成。
代码如下:
#include <cstdio>
#include <cstdlib>
int g_num = 0;
void f(int step, int n);
int main()
{
int n;
printf("pls input n : ");
scanf("%d", &n);
f(1, n);
f(2, n);
printf("the total : %d\n", g_num);
system("pause");
return 0;
}
void f(int step, int n)
{
if (step > n || n == 0)
return;
if (step == n)
{
g_num++;
return;
}
f(1, n-step);
f(2, n-step);
}
总共走法 = 第一次跨一阶的走法 + 第一次跨两阶的走法
递归函数中,若楼梯还没有跨完,则继续选择接下来的一步是跨一阶还是跨两阶。
阿偶,楼梯是跨的还是走的哦,咋个想起跨栏了啊~
n = 1, 2, 3, 4, 5, …… 输出和那个姓f的数列有扯不清的关系~