【C++笔记】全排列问题

问题描述

给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有'a' < 'b' < ... < 'y' < 'z',而且给定的字符串中的字母已经按照从小到大的顺序排列。

常规解法


#include<bits/stdc++.h>
using namespace std;
void fullRank(string pre, string str){
    if(str.size() == 1){//递归终止条件,只剩一个字母的全排列
        cout << pre + str << endl;
        return ;
    }
    //继续递归
    string nextpre = "";
    string nextstr = "";
    for(int i = 0; i < str.size(); i++){
        nextpre = pre + str[i];
        nextstr = str;
        nextstr.erase(i, 1);//剔除该字母
        fullRank(nextpre, nextstr);
    }
}
int main(){
    string str = "";
    cin >> str;
    /*
    递归:
    abc的全排列 = a开头bc的全排列 + b开头ac的全排列 + c开头ab的全排列
    其中,bc的全排列 = b开头c的全排列 + c开头b的全排列
    以此类推......
    */
    fullRank("", str);
    return 0;
}

大佬解法

#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
string s;
map<string,int> mp; 
void swap(char &x,char &y){
    char temp=x;
    x=y;
    y=temp;
}
void dfs(int now){
    if(now==s.size()){
        mp[s]=1;
        return ;
    }
    for(int i=now;i<s.size();i++){
        swap(s[now],s[i]);
        //cout<<"convert to:"<<s<<endl;
        dfs(now+1);
        swap(s[now],s[i]);
        //cout<<"convert back:"<<s<<endl;
    }
}
int main(){
    cin>>s;
    dfs(0);
    for(auto i=mp.begin();i!=mp.end();i++){
        cout<<i->first<<endl;
    }
    return 0;
} 

注:使用map是因为map底层是红黑树,内部有序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值