生成没有重复项的字符串排列

Generating permutation of string without duplicates

本文关键字:字符串 排列      更新时间:2023-10-16

我写了一个通用程序来生成字符串的排列,但删除重复的情况。对于这个,我使用记忆,使用。

void permute(char *a,int i, int n,set<char*> s)
{
    if(i==n)
    {
        if(s.find(a)==s.end()){
            cout<<"no dublicate"<<endl;
            cout<<a<<endl;
            s.insert(a)
        }
    }
    else{
        for(int j=i;j<n;j++)
        {
            swap(a[i],a[j]);
            permute(a,i+1,n,s);
            swap(a[i],a[j]);
        }
    }
}
int main()
{
    char a[]="aba";
    set <char*> s;
    permute(a,0,3,s);
    return 0;
}

但结果并不如所愿。它打印出所有的排列。谁能帮我解决这个问题?

首先,按值传递set<> s参数,这会丢弃每次插入,因为它只在s的本地副本中完成。然而,即使您将其更改为通过引用传递,它也不会工作,因为每次您插入相同的char*值,因此只会完成一次插入。为了使您的代码正确工作,我建议将函数的原型更改为

void permute(string a,int i, int n,set<string>& s)

这个可以正常工作

更新:源代码和描述的小变化

void permute(string a,int i, int n,set<string>& s)
{
    if(i==n)
    {
        if(s.find(a)==s.end()){
            cout<<"no dublicate"<<endl;
            cout<<a<<endl;
            s.insert(a);
        }
    }
    else{
        for(int j=i;j<n;j++)
        {
            swap(a[i],a[j]);
            permute(a,i+1,n,s);
            swap(a[i],a[j]);
        }
    }
}
int main()
{
    string a ="aba";
    set <string> s;
    permute(a,0,3,s);
    return 0;
}