目录
一、问题描述
二、代码
#include <iostream>
#include<stdio.h>
#include<iomanip>
#include<string.h>
using namespace std;
int time=0;//记录排列的总数
template<class Type>
void Swap(Type &a,Type &b)//交换两个数的位置
{
char temp=a;
a=b;
b=temp;
}
template<class Type>
int OK(Type *a,int k,int i)//判断是否有重复元素
{
if(i>k)//保证数组存在的时候
for(int t=k;t<i;t++)//循环查找
{
if(a[t]==a[i])
return 0;
}
return 1;
}
template<class Type>
void Perm(Type *a,int k,int m)//全排列的实现函数
{
if(k==m)//只剩下1个元素
{
time++;//次数+1
for(int i=0;i<=m;i++)
{
cout<<a[i];
}
cout<<"\n";
}
else //还有多个元素待排列
{
for(int i=k;i<=m;i++)//有几个元素就循环几次(因为以它打头,然后对后面的数进行全排列)
{
if(OK(a,k,i))//当不存在重复元素的时候,才进行全排列
{
Swap(a[k],a[i]);//进行交换
Perm(a,k+1,m);
Swap(a[k],a[i]);
}
}
}
}
int main()
{
int n;
cout<<"input.txt"<<endl;
cin>>n;
char r[n];
for(int i=0;i<n;i++)
cin>>r[i];
cout<<"output.txt"<<endl;
Perm(r,0,n-1);
cout<<time;
return 0;
}