一步一步写算法(之爬楼梯)

原贴地址: http://blog.csdn.net/feixiaoxing/article/details/6871148

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】


    前两天上网的时候看到一个特别有意思的题目,在这里和朋友们分享一下:

    有一个人准备开始爬楼梯,假设楼梯有n个,这个人只允许一次爬一个楼梯或者一次爬两个楼梯,请问有多少种爬法?

    在揭晓答案之前,朋友们可以自己先考虑一下:

    这个人爬n层楼梯,那么它也不是一下子就可以爬这么高的,他只有两个选择,要么从n-2层爬过来,要么从n-1层爬过来。除此之外,他没有别的选择。此时相信朋友其实已经早看出来了,这就是一道基本的递归题目。

    (1)首先我们建立一个函数,判断函数的合法性

[cpp]  view plain copy
  1. void jump_ladder(int layer, int* stack, int* top)  
  2. {  
  3.     if(layer <= 0)  
  4.         return;  
  5.   
  6.     return;  
  7. }  

     (2)判断当前的层数是为1或者是否为2

[cpp]  view plain copy
  1. void jump_ladder(int layer, int* stack, int* top)  
  2. {  
  3.     if(layer <= 0)  
  4.         return;  
  5.   
  6.     if(layer == 1){  
  7.         printf_layer_one(layer, stack, top);  
  8.         return;  
  9.     }  
  10.       
  11.     if(layer == 2){  
  12.         printf_layer_two(layer, stack, top);  
  13.         return;  
  14.     }  
  15.   
  16.     return;  
  17. }  
     (3)对于2中提及的打印函数进行设计,代码补全

[cpp]  view plain copy
  1. #define GENERAL_PRINT_MESSAGE(x)\  
  2.     do {\  
  3.         printf(#x);\  
  4.         for(index = (*top) - 1 ; index >= 0; index --)\  
  5.             printf("%d", stack[index]);\  
  6.         printf("\n");\  
  7.     }while(0)  
  8.   
  9. void printf_layer_one(int layer, int* stack, int* top)  
  10. {  
  11.     int index ;  
  12.     GENERAL_PRINT_MESSAGE(1);  
  13. }  
  14.   
  15. void printf_layer_two(int layer, int* stack, int* top)  
  16. {  
  17.     int index;  
  18.       
  19.     GENERAL_PRINT_MESSAGE(11);  
  20.     GENERAL_PRINT_MESSAGE(2);  
  21. }  
    注: a)代码中我们使用了宏,注意这是一个do{}while(0)的结构,同时我们对x进行了字符串强转

             b)当剩下台阶为2的时候,此时有两种情形,要么一次跳完;要么分两次


    (4)当阶梯不为1或者2的时候,此时需要递归处理

[cpp]  view plain copy
  1. void _jump_ladder(int layer, int* stack, int* top, int decrease)  
  2. {  
  3.     stack[(*top)++] = decrease;  
  4.     jump_ladder(layer, stack, top);  
  5.     stack[--(*top)] = 0;  
  6. }   
  7.   
  8. void jump_ladder(int layer, int* stack, int* top)  
  9. {  
  10.     if(layer <= 0)  
  11.         return;  
  12.   
  13.     if(layer == 1){  
  14.         printf_layer_one(layer, stack, top);  
  15.         return;  
  16.     }  
  17.   
  18.     if(layer == 2){  
  19.         printf_layer_two(layer, stack, top);  
  20.         return;  
  21.     }  
  22.   
  23.     _jump_ladder(layer- 1, stack, top, 1);  
  24.     _jump_ladder(layer- 2, stack, top, 2);  
  25. }  
    祝:这里在函数的结尾添加了一个函数,主要是递归的时候需要向堆栈中保存一些数据,为了代码简练,我们重新定义了一个函数。


总结:

    1)这道题目和斐波那契数列十分类似,是一道地地道道的递归题目

    2)递归的函数也需要好好测试,使用不当,极容易堆栈溢出或者死循环。对此,我们可以按照参数从小到大的顺序依次测试,比如说,可以测试楼梯为1、2、3的时候应该怎么运行,同时手算和程序相结合,不断修正代码,完善代码。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值