面试题38:字符串排列
题目描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
代码:
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> result;
if(str.size()==0) return result;
PermutationCore(str,result,0);
sort(result.begin(),result.end());
return result;
}
void PermutationCore(string str,vector<string> &result, int begin){
if(begin==str.size()-1){
if(find(result.begin(),result.end(),str)==result.end()){
result.push_back(str);
}
}
else{
for(int i=begin;i<str.size();i++){
swap(str[i],str[begin]);
PermutationCore(str,result,begin+1);
swap(str[i],str[begin]);
}
}
}
void swap(char &first,char &second){
char temp=first;
first=second;
second=temp;
}
};