Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating permutation of string without duplicates [duplicate]

Tags:

c++

algorithm

set

I have writing a general program to generate permutation of string but removing the duplicate cases . For this I am using memorization by using .

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;
}

But the result is not as desired. It prints all the permutation. Can anyone help me in figuring out the problem.

like image 850
dead programmer Avatar asked Sep 16 '26 11:09

dead programmer


1 Answers

First, you pass set<> s parameter by value, which discards your each insert, because it's done in the local copy of s only. However even if you change it to pass by reference, it won't work, because every time you insert the same char* value, so only one insert will be done. To make your code work correctly I suggest to change the prototype of your function to

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

and this works all right.

update: source code with described minor changes

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;
}
like image 69
Grigor Gevorgyan Avatar answered Sep 18 '26 05:09

Grigor Gevorgyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!