问题:输入一字符串(要求不存在重复字符),打印出该字符串中字符中字符的所有排列。
例如:输入"abc",输出结果为abc, acb, bac, bca, cab和cba。
方法一:比较笨,用一个整型数组,记录当前排列的下标,然后输出下标对应的字符串,空间代价为O(n)
代码:
//参数:字符串,记录当前全排列组合的字符在字符串中的下标,字符串长度,当前要确定的字符
void Permutation(char* letter, int* record, int length, int nCur)
{
if ( nCur == length )
{
static int count = 0;
count++;
cout << count << "->:\t ";
for ( int i = 0; i < length; i++ )
{
cout << letter[record[i]];
}
cout << endl;
return;
}
for ( int i = 0; i < length; i++ )
{
//确定当前结点的字符是什么,不能和已经确定的字符相同
int j;
for ( j = 0; j < nCur; j++ )
{
if ( i==record[j] )
break;
}
if ( j != nCur )
continue;
//确定当前字符
if ( j == nCur )
record[nCur] = i;
Permutation(letter,record,length,nCur+1);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char* letter = "abc";
int length = strlen(letter);
int* record = new int[length];
Permutation(letter,record,length,0);
return 0;
}
方法二:
通过找规律,求字符串的全排列,可以看出三步:
首先,求所有可能出现在第一个位置的字符,
其次,把第一个字符和其后面的字符一一交换。如下图所示,分别把第一个字符a和后面的b、c等字符交换的情形。
接着,固定第一个字符,求后面所有字符的排列。这个时候我们仍把后面的所有字符分成两部分:后面字符的第一个字符,以及这个字符之后的所有字符。然后把第一个字符逐一和它后面的字符交换
代码:
void Permutation_o(char* pStr, char* pBegin)
{
if (*pBegin == '\0' )
cout << pStr <<endl;
else
{
for (char* pCh = pBegin; *pCh!='\0'; pCh++)
{
char temp = *pCh;
*pCh = *pBegin;
*pBegin