3

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
dead programmer
  • 4,223
  • 9
  • 46
  • 77

1 Answers1

3

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;
}
Grigor Gevorgyan
  • 6,753
  • 4
  • 35
  • 64