c++ - 如何只打印字符串的唯一排列?
问题描述
此函数打印字符串的排列,如何修改它以使其仅打印唯一的排列?“没有重复”
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);
解决方案
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");
}
输出:
aaab
aaba
abaa
baaa
推荐阅读
- input - ffmpeg 第一次运行命令时总是给我输入/输出错误
- angular - 使用 HttpClient 模块在 Angular 中出现错误
- mysql - 使用 quarkus 的反应式 MySQL 配置
- bash - 解决了带有变量的 BASH 选项卡完成中的错误
- python - Python将请求响应中的文件内容写入相应文件
- swiftui - SwiftUI 阻止 Divider 在 HStack 中垂直扩展
- r - 为什么“c”在这里等于 1000?
- r - 如何查看/更改 RStudio 使用的 R 安装?
- ios - iOS 本地通知
- java - maven依赖没有正确编译成war