題目描述
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。
tips: 將第一個字符依次與後面的元素交換,遞歸進行
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> res;
if(str=="") {
return res;
} else if(str.size()==1) {
res.push_back(str);
return res;
}
char temp=str[0];
for (int i = 0; i < str.length(); i++)
{
if(i==0 || str[0]!=str[i]) {
// 交換i 和 0 處的字符
temp=str[0];
str[0]=str[i];
str[i]=temp;
vector<string> str_list = Permutation(str.substr(1,str.length()-1));
for (int j = 0; j < str_list.size(); j++)
{
string str_one = str[0]+str_list[j];
res.push_back(str_one);
}
// 換回來
temp=str[0];
str[0]=str[i];
str[i]=temp;
}
}
sort(res.begin(),res.end());
return res;
}
};