有重复元素的排列问题

#include<iostream>
using namespace std;
int ans; //计数器

//自定义内联函数Swap
template <class Type>
inline void Swap(Type &a,Type &b)
{
   Type temp=a;
   a=b;
   b=temp;
}

//判断是否有重复元素
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 Perm(Type list[],int k,int m){
     if(k==m)
     {
        ans++;
        for(int i=0;i<=m;i++)
        cout<<list[i];
        cout<<endl;
     }
     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]);
       }
     }
}

int main()
{
    ans=0;
    int n;
    char sample[999];
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>sample[i];
    Perm(sample,0,n-1);
    cout<<ans<<endl;
    return 0;
}

运行截图:


猜你喜欢

转载自blog.csdn.net/geliaozhang/article/details/80482109