[英]how can print only unique Permutations of a string?
这个 function 打印字符串的排列,我该如何修改它以使其仅打印唯一的排列? “没有重复”
void RecPermute(string soFar, string rest) {
if (rest == "") // No more characters
cout << soFar << endl; // Print the word
else // Still more chars
// For each remaining char
for (int i = 0; i < rest.length(); i++) {
string next = soFar + rest[i]; // Glue next char
string remaining = rest.substr(0, i) + rest.substr(i + 1);
RecPermute(next, remaining);
}
}
// "wrapper" function
void ListPermutations(string s) {
RecPermute("", s);
您可以使用创建唯一排列的标准 function std::next_permutation
。
例子:
#include <algorithm>
#include <iostream>
#include <string>
void ListPermutations(std::string str) {
std::sort(str.begin(), str.end()); // sort to start at the first permutation
do {
std::cout << str << '\n';
// get the next unique permutation:
} while( std::next_permutation(str.begin(), str.end()) );
}
int main() {
ListPermutations("aaba");
}
Output:
aaab
aaba
abaa
baaa
如果你不允许使用任何库 function 像std::next_permutation
,你可以使用回溯和递归来解决这个问题。 该算法与具有唯一字符的排列相同,但您需要检查之前是否遇到过该数字。 如果以前遇到过字符,请忽略它以避免重复。
这是带有注释的代码:
#include <iostream>
#include <string>
#include <set>
void printPermutations(std::string &str, int index) {
if (index == str.size()) {
std::cout << str << std::endl;
return;
}
std::set<char> soFar;
// loop from position index onward
for (auto i = index; i < str.size(); i++) {
// check we haven't seen character in loop previously
if (soFar.find(str[i]) == soFar.end()) {
// store character in set
soFar.insert(str[i]);
// swap index with next character in loop
std::swap(str[index], str[i]);
printPermutations(str, index + 1);
// swap back
std::swap(str[index], str[i]);
}
}
}
// "wrapper" function
void ListPermutations(std::string s) {
printPermutations(s, 0);
}
int main()
{
ListPermutations("aaba");
return 0;
}
Output:
aaba
aaab
abaa
baaa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.