【问题标题】:Generating permutation of string without duplicates [duplicate]生成没有重复的字符串排列[重复]
【发布时间】:2013-03-22 05:09:13
【问题描述】:

我编写了一个通用程序来生成字符串排列但删除重复的情况。为此,我使用 . 进行记忆。

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

但结果并不如预期。它打印所有排列。谁能帮我解决问题。

【问题讨论】:

  • 什么是“复制”?
  • 你的意思是你想要组合而不是排列?
  • 你试过 std::next_permutation 了吗?
  • 对于那些询问他对重复项是什么意思的人,我认为他的意思是(给定输入“aab”)他不希望“aab”返回两次(一次是原始字符串,一次是第一个和第二个a 被置换)。

标签: c++ algorithm set


【解决方案1】:

首先,您通过值传递set&lt;&gt; 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;
}

【讨论】:

  • 上述原型不工作。您能否使用 codepad.org 分享您的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多