[英]How can I remove duplicated permutations in C++
#include <iostream>
using namespace std;
void RecPermute(string soFar, string rest)
{
if (rest == "") {
cout << soFar << endl;
}
else {
for (int i = 0; i < rest.length(); i++) {
string next = soFar + rest[i];
string remaining = rest.substr(0, i) + rest.substr(i + 1);
RecPermute(next, remaining);
}
}
}
void ListPermutations(string s) {
RecPermute("",s);
}
int main()
{
RecPermute("", "aab");
return 0;
}
I am doing a college task, the task is to use this code to print characters permutations.我正在做一个大学任务,任务是使用这个代码来打印字符排列。 this code is doing this but repeated characters result in repeated words.
此代码正在执行此操作,但重复的字符会导致重复的单词。 for example, if I entered "aab" the output will be: aab aba aab aba baa baa
例如,如果我输入“aab”,则 output 将是:aab aba aab aba baa baa
This is the example source code from cppreference's std::next_permutation entry .这是来自 cppreference 的std::next_permutation entry的示例源代码。 It does exactly what you want and automatically does not include duplicates:
它完全符合您的要求,并且自动不包含重复项:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
std::string s = "aba";
std::sort(s.begin(), s.end());
do {
std::cout << s << '\n';
} while(std::next_permutation(s.begin(), s.end()));
}
Output: Output:
aab
aba
baa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.