题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路:回溯
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> res;
if(str == "") return res;
dfs(str,res,0);
sort(res.begin(),res.end());
res.erase(unique(res.begin(),res.end()),res.end());//unique()用于去重
return res;
}
void dfs(string str,vector<string> &res,int i){
if(i == str.size()-1){//到了叶子结点,即结果在叶结点中
res.push_back(str);
return ;
}
for(int j = i;j < str.size();j++){
if(str[i] != str[j] || i == j){
swap(str[i],str[j]);//执行当前结点到子结点对应操作
dfs(str,res,i+1);//对子结点重复同样操作
swap(str[i],str[j]);//复原
}
}
}
};