问题描述
给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有'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底层是红黑树,内部有序