You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.3 KiB
57 lines
1.3 KiB
#include <iostream>
|
|
#include <cstring>
|
|
|
|
//全排列代码说明
|
|
|
|
// https://www.jianshu.com/p/e0de4c9b73f2?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
|
|
|
|
using namespace std;
|
|
|
|
//在[from, to]区间中是否有字符与下标为from的字符相等
|
|
bool IsSwap(char* from, char* to)
|
|
{
|
|
char* p;
|
|
for(p = from; p < to; p++)
|
|
{
|
|
if(*p == *to)
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void AllPermutation(char* perm, int from, int to)
|
|
{
|
|
if(from > to)
|
|
return;
|
|
|
|
if(from == to) //打印当前排列
|
|
{
|
|
static int count = 1; //局部静态变量,用来统计全排列的个数
|
|
cout << count++ << ":" << perm;
|
|
cout << endl;
|
|
}
|
|
if(from < to) //用递归实现全排列
|
|
{
|
|
for(int j = from; j <= to; j++) //第j个字符分别与它后面的字符交换就能得到新的排列
|
|
{
|
|
if(IsSwap((perm + j), (perm + to)))
|
|
{
|
|
swap(perm[j], perm[from]);
|
|
//cout<<0;
|
|
AllPermutation(perm, from + 1, to);
|
|
//cout<<1;
|
|
swap(perm[j], perm[from]);
|
|
//cout<<2;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
char str[100];
|
|
cin >> str;
|
|
AllPermutation(str, 0, strlen(str) - 1);
|
|
return 0;
|
|
}
|