输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路:
链接:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
来源:牛客网
基于回溯法思想:
class Solution {
void swap(char &ele1, char &ele2){
char tmp = ele1;
ele1 = ele2;
ele2 = tmp;
}
void PermutationHepler(string str, vector<string> &res, int begin){
if (begin == str.size()-1){
if (find(res.begin(), res.end(), str) == res.end())
res.push_back(str);
} else {
for(int i = begin; i < str.size(); i++){
swap(str[i], str[begin]);
PermutationHepler(str, res, begin+1);
swap(str[i], str[begin]);
}
}
}
public:
vector<string> Permutation(string str) {
vector<string> res;
if (str.empty())
return res;
PermutationHepler(str, res, 0);
sort(res.begin(), res.end());
return res;
}
};