首页
外语
计算机
考研
公务员
职业资格
财经
工程
司法
医学
专升本
自考
实用职业技能
登录
计算机
输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
admin
2019-03-29
60
问题
输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
选项
答案
void Permutation(char* pStr, char* pBegin); ///////////////////////////////////////////////////////////////////////// // Get the permutation of a string, // for example, input string abc, its permutation is // abc acb bac bca cba cab ///////////////////////////////////////////////////////////////////////// void Permutation(char* pStr) { Permutation(pStr, pStr); } ///////////////////////////////////////////////////////////////////////// // Print the permutation of a string, // Input: pStr - input string // pBegin - points to the begin char of string // which we want to permutate in this recursion ///////////////////////////////////////////////////////////////////////// void Permutation(char* pStr, char* pBegin) { if(!pStr || !pBegin) return; // if pBegin points to the end of string, // this round of permutation is finished, // print the permuted string if(*pBegin == ’\0’) { printf("%s\n", pStr); } // otherwise, permute string else { for(char* pCh = pBegin; *pCh != ’\0’; ++ pCh) { // swap pCh and pBegin char temp = *pCh; *pCh = *pBegin; *pBegin = temp; Permutation(pStr, pBegin + 1); // restore pCh and pBegin temp = *pCh; *pCh = *pBegin; *pBegin = temp; } } }
解析
这是一道很好的考查对递归理解的编程题,因此在过去一年中频繁出现在各大公司的面试、笔试题中。
我们以三个字符abc为例来分析一下求字符串排列的过程。首先我们固定第一个字符a,求后面两个字符bc的排列。当两个字符bc的排列求好之后,我们把第一个字符a和后面的b交换,得到bac,接着我们固定第一个字符b,求后面两个字符ac的排列。现在是把c放到第一位置的时候了。记住前面我们已经把原先的第一个字符a和后面的b做了交换,为了保证这次c仍然是和原先处在第一位置的a交换,我们在拿c和第一个字符交换之前,先要把b和a交换回来。在交换b和a之后,再拿c和处在第一位置的a进行交换,得到cba。我们再次固定第一个字符c,求后面两个字符b、a的排列。
既然我们已经知道怎么求三个字符的排列,那么固定第一个字符之后求后面两个字符的排列,就是典型的递归思路了。
转载请注明原文地址:https://kaotiyun.com/show/0RmZ777K
0
程序员面试
相关试题推荐
TheUnitedStatesInterstateHighwaySystemisaninfrastructurefeatofunprecedentedproportions.Notonlydoesitjoinallfi
[A]Theperson-skillsmatchapproachtoselection[B]Theimpactsofbadselectiondecisions[C]Theimportanceofstructu
输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次。
公司要求开发一个继承System.Windows.Forms.ListView类的组件,要求达到以下的特殊功能:点击ListView各列列头时,能按照点击列的每行值进行重排视图中的所有行(排序的方式如DataGrid相似)。根据您的知识,请简要谈一下您的
ASP.net的身份验证方式有哪些?分别是什么原理?
输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:structListNode{intm_nKey;ListNode*m_pNext;};
数据库的优化设计?
自定义工具栏上的按钮添加“自动索引”按钮,删除“查找”按钮。
利用MSN给bob@sina.com发送电子邮件内容“8号晚上到我家一起吃饭”。
随机试题
锁骨正位片:锁骨显示为“~”形弯曲为
患者患慢性乙型肝炎后肝硬化2年,症见腹水、下肢水肿。引起水肿的主要相关因素是()
最早创用苇茎汤治疗肺痈的是()
A.推动作用B.温煦作用C.防御作用D.固摄作用E.气化作用“宗气……贯心脉而行呼吸”是指气的
下列不能体现工程造价资料数据库作用的是()。
背景材料:某施工单位承接了一4×20m简支梁桥工程。桥梁采用扩大基础,墩身平均高10m。项目为单价合同,且全部钢筋由业主提供,其余材料由施工单位自采或自购。在离本工程不远的江边有丰富的砂源,经检验,砂的质量符合要求。采砂点位于
关于财务战略矩阵的说法中,正确的有()。
一、注意事项1.申论考试与传统的作文考试不同,是分析驾驭材料的能力与表达能力并重的考试。2.作答参考时限:阅读资料40分钟,作答110分钟。3.仔细阅读给定的资料,按照后面提出的“作答要求”依次作答在答题纸指定位置。
沃尔夫通讯社
A、 B、 C、 D、 A
最新回复
(
0
)