C++作业03_02: 下楼问题。从楼上走到楼下共有h个台阶,每一步有三种走法

来源:互联网 发布:安卓mac地址修改器 编辑:程序博客网 时间:2024/04/29 23:37
/*作业03, 练习2下楼问题。从楼上走到楼下共有h个台阶,每一步有三种走法:走1个台阶,走2个台阶,走3个台阶。问有多少可走的方案。用递归思想编程。*/#include <stdio.h>#include <string.h>#include <stdlib.h>static int stack[1024];       // 存放每一步的台阶数static int steps = 0;         // 走过的步数static int num_of_method = 0; // 多少种走法void NextStairs(int n){if(n == 0){/* 走完所有台阶,打印本次的走法,即曾经走过的步骤 */printf("第%3d种走法[需%3d步] : ", ++num_of_method, steps);int i;for(i=0; i<steps; i++)printf("%d ", stack[i]);printf("\n");return;}if(n >= 1){stack[steps++] = 1; // 本次走1个台阶NextStairs(n-1);steps --; }if(n >= 2){stack[steps++] = 2; // 本次走2个台阶NextStairs(n-2);steps --;}if(n >= 3){stack[steps++] = 3; // 本次走3个台阶NextStairs(n-3);steps --;}}int ex03_02(){int n;printf("enter a positive number: n=");scanf("%d", &n);NextStairs(n);return 0;}