1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
ACM1.2 总结 杨国东 2005-10-26 练习一:回溯生成一组字母有限重全排列 Description You are to write a program that has to generate all possible words from a given set of letters. Example: Given the word abc, your program should - by exploring all different combination of the three letters - output the words abc, acb, bac, bca, cab and cba. In the word taken from the input file, some letters may appear more than once. For a given word, your program should not produce the same word more than once, and the words should be output in alphabetically ascending order Input The input consists of several words. The first line contains a number giving the number of words to follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A to Z. Uppercase and lowercase letters are to be considered different. The length of each word is less than 13 Output For each word in the input, the output should contain all different words that can be generated with the letters of the given word. The words generated from the same input word should be output in alphabetically ascending order. An upper case letter goes before the corresponding lower case letter. 题意分析 形式化描述 给定p1,p2,…,pn,求p1,p2,…,pn的一个全排列 注意:p值可以重复 回溯算法 a,b,c生成的一棵搜索树 a,a,c生成的一棵搜索树 递归回溯 n为输入的字母个数 x用于存储生成的关于输入的一个排列 消重 for循环消重,扩展constraint( t ) for遍历,增强constraint( t ) for循环消重,扩展constraint( t ) for(p1,p2,…,pr),其中p1,p2,…,pr为p1,p2,…,pn中不重复的字母 constraint( t ) 用于判断h( i )是否已经被用过 扩展到判断h( i )是否已经被用过它的重复度次数。为每个字母建立一个引用计数(扩充标志位),初始值为其重复度,每使用一次引用计数减1,当计数为0时返回false,否则返回true,扩展的是标志位? 源码样板 编码的技巧,特定的应用场景 两种实现 计数 排序替代 //tier为层数,即result正在处理的位数 void backtrack( int tier ) { int totaltier = str.size() - 1; //最高层数(起始层为0) int num;//记录本层可选择字母的序号 if( tier totaltier ){ //已到达最高层 //输出 result[str.size()] = \0; cout result endl; } else for( num = 0; num new_str.size(); num++ ) { //new_str.size()为可选择的字母总数 result[tier] = new_str[num]; count[num]--;//某一字母变成选择

文档评论(0)

bhl0572 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档