题解 | #全排列# 直接输出字典序的快速方法

全排列

https://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1

直接在字符串上操作,不需要拷贝!!!!!

直接输出字典序而不需要重新排序!!!!!

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

void permutation(string& str, int s) {
    if (s == str.size()) {
        cout << str << endl;
        return;
    }
    for (auto i = s; i < str.size(); i++) {
        swap(str[s], str[i]);
        permutation(str, s + 1);
    }
    auto c = str[s];
    for (auto i = s + 1; i < str.size(); i++) {
        str[i - 1] = str[i];
    }
    str[str.size() - 1] = c;
}

int main() {
    string str;
    cin >> str;
    sort(str.begin(), str.end());
    permutation(str, 0);
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务