#include<bits/stdc++.h>
using namespace std;
int vis[100];//标记
int a[100];//记录
int n;
void fun(int step)
{
if(step==n)
{
for(int i=0;i<n;++i)
{
cout<<a[i];//若是给定一个字符串:cout<<s[a[i]-1];将a[i]-1做下标
}
cout<<endl;
}
else
{
for(int i=1;i<=n;++i)
{
if(vis[i]==0)
{
vis[i]=1;
a[step]=i;
fun(step+1);
vis[i]=0;//还原
}
}
}
}
int main()
{
cin>>n;
fun(0);
return 0;
}
运行
字符串版:
#include<bits/stdc++.h>
using namespace std;
int vis[100]={
0};//标记
int a[100];//记录
//int n;
string s;
void fun(int step)
{
if(step==s.size())
{
for(int i=0;i<s.size();++i)
{
cout<<s[a[i]-1];
}
cout<<endl;
}
else
{
for(int i=1;i<=s.size();++i)
{
if(vis[i]==0)
{
vis[i]=1;
a[step]=i;
fun(step+1);
vis[i]=0;//还原
}
}
}
}
int main()
{
cin>>s;
fun(0);
return 0;
}
运行:
使用全排列函数
next_permutation()返回false时循环结束,使用前需要用sort整理
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[101];
int n;
cin>>s;
sort(s,s+strlen(s));
do//全排列函数
{
for(int i=0;i<strlen(s);++i)
{
cout<<s[i];
}
cout<<endl;
}while(next_permutation(s,s+strlen(s)));
return 0;
}
运行
若不用do while,而是while,abc原字符串不输出
如果不用sort整理