题目
一共39层台阶。如果我每一步迈上1个台阶或者两个台阶,先迈左脚,再迈右脚,然后左右交换,最后一步迈右脚,也就是一共要走偶数步,那么,上完39级台阶,有多少种不同的方法?
思路
采用递归的思想,边界条件就是台阶上数小于0,返回0;台阶上等于0,而且步数恰好是偶数步,那么说明走完了所有台阶,方法加1.
代码
#include<stdio.h>
#include<stdlib.h>
int count_way = 0;
int Sum(int left_stair, int step)
{
if(left_stair < 0)
return 0;
if(left_stair == 0 && step % 2 == 0)
{
count_way++;
return 0;
}
Sum(left_stair - 1, step+1);//一次迈一层台阶
Sum(left_stair - 2, step+1);//一次迈两层台阶
}
int main(void)
{
int n;
printf("enter n:");
scanf("%d", &n);
Sum(n, 0);
printf("Total = %d
", count_way);
return 0;
}