1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
class Solution { public: string path; vector<string> res; vector<bool> visited;
vector<string> Permutation(string str) { path = str; visited = vector<bool>(str.size()); sort(str.begin(), str.end()); dfs(str, 0); return res; }
void dfs(string& s, int idx) { if (idx == s.size()) { res.push_back(path); return; }
for (int i = 0; i < s.size(); i ++) { if (!visited[i]) { if (i && s[i] == s[i - 1] && !visited[i - 1]) continue; visited[i] = true; path[idx] = s[i]; dfs(s, idx + 1); path[idx] = ' '; visited[i] = false; } } } };
class Solution { public: vector<string> res;
vector<string> Permutation(string str) { if (str.size() == 0) return {}; PermutationCore(str, 0, str.size() - 1); sort(res.begin(), res.end()); return res; }
void PermutationCore(string& s, int begin, int end) { if (begin == end) { res.push_back(s); return; }
unordered_map<int, bool> visited; for (int i = begin; i <= end; i ++) { if (visited[s[i]]) continue; visited[s[i]] = true; swap(s[i], s[begin]); PermutationCore(s, begin + 1, end); swap(s[i], s[begin]); } } };
vector<string> Permutation(string str) { if (str.size() == 0) return {};
vector<string> res; sort(str.begin(), str.end()); do { res.push_back(str); } while (next_permutation(str.begin(), str.end()));
return res; }
|