思路:使用 STL 库中的 next_permutation 函数进行全排列,然后依次输出序列即可,注意去重。

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    int n;
    string str;
    cin >> n >> str;
    sort(str.begin(), str.end()); // 排序以确保字典序
    do {
        cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));
    cout << endl;
    return 0;
}

输入格式

1 <= n <= 500

输出格式

每行一个序列,按字典序输出,最后一行输出方案数

输入样例

4 aacc

输出样例

aacc acac acca caac caca ccaa 6

C++ STL next_permutation 实现字符串全排列 (含重复元素)

原文地址: https://www.cveoy.top/t/topic/n2nD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录