输入一个字符串,其含有的字符不同。程序输出该字符串的所有全排列。
1.用递归调用实现:代码如下
#include<iostream>
using namespace std;
using namespace std;
void swap(int &x,int &y) //交换函数
{
int t;
t = x;
x = y;
y = t;
}
{
int t;
t = x;
x = y;
y = t;
}
void AllPermutation(char *perm, int left, int right) //全排列
{
if (right < 0)
return ;
{
if (right < 0)
return ;
int i = 0;
if (left == right)
{
for (i = 0; i <= right; i++)
{
cout << perm[i];
}
cout << endl;
}
else
{
for (i = left; i <= right; i++)
{
swap(perm[i], perm[left]);//交换
AllPermutation(perm, left + 1, right);//递归
swap(perm[i], perm[left]);//还原
}
}
if (left == right)
{
for (i = 0; i <= right; i++)
{
cout << perm[i];
}
cout << endl;
}
else
{
for (i = left; i <= right; i++)
{
swap(perm[i], perm[left]);//交换
AllPermutation(perm, left + 1, right);//递归
swap(perm[i], perm[left]);//还原
}
}
}
int main()
{
char s[] = "abc";
AllPermutation(s,0,2);
int main()
{
char s[] = "abc";
AllPermutation(s,0,2);
return 0;
}
}
2.另一种写法:
#include<iostream>
#include<assert.h>
using namespace std;
#include<assert.h>
using namespace std;
void swap(int &x,int &y)
{
int t;
t = x;
x = y;
y = t;
}
{
int t;
t = x;
x = y;
y = t;
}
void Permutation(char* pStr, char* pBegin)
{
assert(pStr!=NULL && pBegin!=NULL);
{
assert(pStr!=NULL && pBegin!=NULL);
if (*pBegin == '\0')
printf("%s\n", pStr);
else
{
for (char* pCh = pBegin; *pCh!= '\0'; pCh++)
{
swap(*pBegin, *pCh);
Permutation(pStr, pBegin + 1);
swap(*pBegin, *pCh);
}
}
}
printf("%s\n", pStr);
else
{
for (char* pCh = pBegin; *pCh!= '\0'; pCh++)
{
swap(*pBegin, *pCh);
Permutation(pStr, pBegin + 1);
swap(*pBegin, *pCh);
}
}
}
int main()
{
char s[] = "abc";
//AllPermutation(s,0,2);
Permutation(s, s);
{
char s[] = "abc";
//AllPermutation(s,0,2);
Permutation(s, s);
return 0;
}
}