8594 有重复元素的排列问题
时间限制:1000MS 内存限制:1000K
描述
Input
第1行是元素个数n,1<=n<=15。接下来的1行是待排列的n个元素,元素中间不要加空格。
Output
程序运行结束时,将计算出输n个元素的所有不同排列。最后1行中的数是排列总数。
Sample Input
4
aacc
Sample Output
aacc
acac
acca
caac
caca
ccaa
6
#include<iostream>
#include"stdio.h"
#include"stdlib.h"
int w=0;
using namespace std;
template <class Type>
int OK(Type list[],int k,int i)
{
if(i>k)
for(int t=k;t<i;t++)
if(list[t]==list[i])
return 0;
return 1;
}
template <class Type>
void Swap(Type &a,Type &b)
{
Type temp=a;
a=b;
b=temp;
}
template <class Type>
int Perm(Type list[],int k,int m)//产生list[k:m]的所有排列
{
if(k==m)//只剩下一个元素
{
for(int i=0;i<=m;i++)
cout<< list[i];
cout<< endl;
w++;
}
else//还有多个元素待排列,递归产生排列
for(int i=k;i<=m;i++)
if(OK(list,k,i))
{
Swap(list[k],list[i]);
Perm(list,k+1,m);
Swap(list[k],list[i]);
}
return w;
}
int main()
{
char list[100];
int i,n,k=0;
cin>> n;
getchar();
for(i=0;i<n;i++)
{
cin>> list[i];
}
cout<<Perm(list,k,n-1);
system("pause");
return 0;
}