题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
DFS + 回溯
class Solution { public: void perm(int start, string str, set<string> &ans) { if (start + 1 == str.size()) { ans.insert(str); return; } for (int i = start; i < str.size(); ++i){ if (i > start && str[i] == str[i-1]) continue; // 去重 swap(str[start], str[i]); perm(start+1, str, ans); swap(str[start], str[i]); } } vector<string> Permutation(string str) { if (str.empty()) return {}; set<string> ans; sort(str.begin(), str.end()); perm(0, str, ans); return vector<string>{ans.begin(), ans.end()}; } };