我们知道,n个不同的元素共有你n!中排列,但对于包含相同的元素,则排列数则没有则这么多,如n个元素,扣除重复的元素后有m个,则排列数>=m! 而小于等于n!
例如,包含3个元素的数组{2,2,3} 有3种排列
{2,2,3}
{2,3,2}
{3,2,2}
贴上代码:
#include<iostream>
using namespace std;
int time = 0;
// 交换
template<class Type>
void Swap(Type &a, Type &b){
Type temp = a;
a = b;
b = temp;
}
template<class Type>
bool Repeat(Type *a,int k,int i)///判断是否有重复元素
{
for(int t=k;t<i;t++)///循环查找
{
if(a[t]==a[i])
return false;
}
return true;
}
// 全排列算法,每次只取一个出来,r1Perm(R1)表示Perm中不含r1,并且由r1开头。
template<class Type>
void Perm(Type *list,int k, int m){ // 产生list[k:m]的所有排列
if(k == m){ //递归的出口 只剩下一个元素
time ++; //记录排列数
for(int i=0; i<=m; i++){
cout << list[i]<<" ";
}
cout << endl;
}
else{ // 还有多个元素待排列,递归产生排列
for(int i=k; i<=m; i++){
if(Repeat(list,k,i))///当不存在重复元素的时候,才进行全排列
{
Swap(list[k],list[i]);
Perm(list, k+1, m);
Swap(list[k], list[i]);
}
}
}
}
// 主函数测试
int main(){
char a[4] = {'1','2','4','4'};
Perm(a,0,3);
cout <<"輸出排列的總列數為:\t"<<time<< endl;
system("pause");
return 0;
}