题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路:实际上本题需要排除重复情况,结果需要字典排序
可以参考博客:
https://www.cnblogs.com/AndyJee/p/4655485.html
class Solution {
public:
vector<string> Permutation(string str) {
if(str.length() <= 0)
return result;
permu(str,0);
sort(result.begin(),result.end());
return result;
}
void permu(string str,int begin){
if(begin == str.length()-1) //最后一个字符的自身交换可以不考虑,如果考虑就不减1
result.push_back(str);
else{
for(int i = begin;i<str.length();i++){
if(begin == i || str[begin] != str[i]){ //排除重复的影响
swap(str[begin],str[i]);
permu(str,begin+1);
swap(str[begin],str[i]); //采用回溯的方法
}
}
}
}
void swap(char& a,char& b){
char temp = a;
a=b;
b=temp;
}
private:
vector<string> result;
};