题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路
比如abca
先固定a为第一位,如果后面某位和第一位不同就换位置,如果相同(最后一个a)就不换
换位置以后把,后面的当成一个新字符串重复以上操作,一直到结束(找到一个序列),然后在换回来
code
class Solution {
public:
void Permutation(string str,int begin,vector<string >&res){
if(begin==(str.size()-1)){
res.push_back(str);
}
for(int i=begin;i<str.size();++i){
if(i!=begin&&str[i]==str[begin]){
continue;
}
swap(str[i],str[begin]);
Permutation(str,begin+1,res);
swap(str[i],str[begin]);
}
}
vector<string > Permutation(string str) {
vector<string >res;
if(str.size()==0)
return res;
Permutation(str,0,res);
sort(res.begin(),res.end());
return res;
}
};