设为首页 加入收藏

TOP

2.3 执行动作的递归(2)
2014-03-11 13:04:51 来源: 作者: 【 】 浏览:127
Tags:2.3 执行 动作

2.3  执行动作的递归(2)

注释:writeBackward不返回计算值

 

另一个解决方案  现在看一个稍有些不同的问题解决方案。回想一下,从字符串中去掉字符有两种选择:去掉最后一个字符或去掉第一个字符。上述解决方案去掉字符串的最后一个字符。下面将根据第二种选择创建解决方案:

去掉第一个字符

开始时,考虑对前述伪代码解决方案的简单修改,用first替换last。这样,函数输出第一个字符,而不是最后一个,然后递归地逆置字符串的其余部分。
 

  1. writeBackward1(s: string)  
  2. if (the string s is empty)  
  3. Do nothing —this is the base case  
  4. else  
  5. {  
  6. Write the first character of s  
  7. writeBackward1(s minus its first character)  
  8. }  

此解决方案能达到预期效果吗?仔细分析可知,它按一般的从左至右方向输出字符串,而不是逆置。伪代码中的步骤为:

输出s的第一个字符

输出s的其余部分

这些步骤仅输出字符串s。虽将函数命名为writeBackward,但并没有真正逆置字符串--递归不是万能的。

可通过下列递归描述来正确地逆置s:

去掉第一个字符,然后逆置字符串s

输出字符串s的第一个字符

换句话说,先逆置s的其余部分,再输出s的第一个字符。这种方法的伪代码解决方案如下所示:
 

  1. writeBackward2(s: string)  
  2. if (the string s is empty)  
  3. Do nothing —this is the base case  
  4. else  
  5. {  
  6. writeBackward2(s minus its first character)  
  7. Write the first character of s  
  8. }  

writeBackward2转换得到的C++代码与原始writeBackward函数类似,我们将此留作练习。

在此有必要仔细跟踪上述两个伪代码函数writeBackward和writeBackward2的操作。首先在各个函数中添加语句,以提供有利于跟踪的输出。
 

  1. writeBackward(s: string)  
  2. cout << "Enter writeBackward with string: " << s << endl;  
  3. if (the string is empty)  
  4. Do nothing —this is the base case  
  5. else  
  6. {  
  7. cout    << "About to write last character of string: "  
  8. << s << endl;  
  9. Write the last character of s  
  10. writeBackward(s minus its last character) // Point A  
  11. }  
  12. cout << "Leave writeBackward with string: " << s << endl;  
  13. writeBackward2(s: string)  
  14. cout    << "Enter writeBackward2 with string: "  
  15. << s << endl;  
  16. if (the string is empty)  
  17. Do nothing —this is the base case  
  18. else  
  19. {  
  20. writeBackward2(s minus its first character) // Point A  
  21. cout    << "About to write first character of string: "  
  22. << s << endl;  
  23. Write the first character of s  
  24. }  
  25. cout << "Leave writeBackward2 with string: " << s << endl;  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3 执行动作的递归(1) 下一篇2.3 执行动作的递归(3)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·HTTPS 详解一:附带 (2025-12-26 02:20:37)
·TCP/IP协议到底在讲 (2025-12-26 02:20:34)
·TCP和UDP在socket编 (2025-12-26 02:20:32)
·有没有适合新手练习 (2025-12-26 01:48:47)
·用清华镜像网怎么下 (2025-12-26 01:48:44)