輸入一個字符串,打印出該字符串中字符的所有排列。例如輸入字符串abc,則輸出由字符a、b、c所能排列出來的所有字符串abc、acb、bac、bca、cab和cba。
我們以三個字符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的排列。
既然我們已經知道怎麼求三個字符的排列,那麼固定第一個字符之後求後面兩個字符的排列,就是典型的遞歸思路了。
基於前面的分析,我們可以得到如下的參考代碼:
void Permutation(char* pStr, char*
pBegin);
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;
}
}
}
轉貼自:http://zhedahht.blog.163.com/blog/static/254111742007499363479/