【牛客网】KY43 全排列

在这里插入图片描述
这道题需要用到递归的思想,可以将字符串分为两部分,一部分为已经排列好的,另一部分为待排列的,然后对待排列的部分依次遍历选择一个字符放到已经排列好的部分中,依次递归直至所有字符都已排列好为止:

// #include <bits/stdc++.h>
// using namespace std;
// int main(){
//     for(string s;cin>>s;cout<<endl){
// 		sort(s.begin(),s.end());
// 		for(cout<<s<<endl;next_permutation(s.begin(),s.end());cout<<s<<endl);
//     }
//     return 0;
// }

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

void func(string s, int n){
    if(n == 1) cout<<s<<endl;
    else{
        int len = s.size();
        for(int i = 0;i < n;i++){
            string temp(s);
            char ch = temp[len - n + i];  //从待排列的部分中依次选择一个字符
            temp.erase(len - n + i, 1);  //将该字符从原来的位置移动到新的位置上
            temp.insert(len - n, 1, ch);
            func(temp, n - 1);
        }
    }
}

int main(){
    string s;
    while(cin>>s){
        sort(s.begin(), s.end());  //将字符串按照字典序进行排列
        func(s, s.size());
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值