题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
题目分析
剑指Offer(纪念版)P154
代码实现
回溯法--排序树
void Permutation(char* pStr)
{
if(pStr == NULL)
return;
Permutation(pStr, pStr);
}
void Permutation(char* pStr, char* pBegin)
{
if(*pBegin == ' ')
{
printf("%s
", pStr);
}
else
{
for(char* pCh = pBegin; *pCh != ' '; ++ pCh)
{
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
Permutation(pStr, pBegin + 1);
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
}
}
}