生成没有重复项的字符串排列
Generating permutation of string without duplicates
我写了一个通用程序来生成字符串的排列,但删除重复的情况。对于这个,我使用记忆,使用。
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;
}
相关文章:
- 找到具有最多子串栅栏的字符串排列
- 为什么我得到长度仅为 3 的字符串排列的输出?
- 如何排列二进制字符串以最小化它们之间的距离
- C++按字母顺序排列的字符串数组
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 如何在 c++ 中按字母顺序排列数组中的字符串?
- 在c++中生成字符串的排列
- 从给定字符串中查找长度 k 的所有排列/组合
- C++ 字符串的排列,输出的结果小于或等于字符串的长度
- 生成具有条件的给定字符串的排列
- 从左到右打印字符串的组合(不是排列)c++
- 如何找到通过仅移动相邻字符创建的字符串的排列?-C++
- 如何在C++中分隔和排列名字和全名字符串
- 如何从长度为 n 的字符串中获取 lengh k 的所有唯一排列的数量
- 它如何排列单词以使用 qsort 和字符串
- 非递归二进制字符串排列生成器
- 生成没有重复项的字符串排列
- 字符串排列:如何去除重复排列
- 什么是可以高效打印字符串排列的算法?
- 字符串排列