题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
template <typename T>
void myswap(T &a,T &b)
{
T temp=a;
a=b;
b=temp;
}
class Solution {
public:
vector<string>& Permutation(string str) {
vector<string>* res;
res=recurbuild(str,str.size()-1);
sort(res->begin(),res->end());//排序
auto iter=unique(res->begin(),res->end());//去重
res->erase(iter,res->end()); //清除
return *res;
}
vector<string>* recurbuild(string str,int end)
{
if(end==0)
{
vector<string>* res=new vector<string>{};
res->push_back(str.substr(end,1));
return res;
}
vector<string>* res=new vector<string>{};
for(int i=end;i>=0;--i)//从后向前递归,降低字符串移动次数
{
if(str[i]!=str[end])
myswap(str[i],str[end]);
vector<string>* sta=recurbuild(str,end-1);
for(auto c:*sta)
res->push_back(c+str[end]);
delete sta;//释放递归分配的空间
}
return res;
}
};