JZ27 字符串的排列
本文最后更新于:2022年4月9日 中午
Solution
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
| class Solution { public: vector<string> Permutation(string s) { int n = s.size(); if (n == 0) return res; sort(s.begin(), s.end());
string record; used = vector<bool>(n, false); backtrack(s, record); return res; }
private: vector<bool> used; vector<string> res;
void backtrack(string& s, string& record) { if (record.size() == s.size()) { res.push_back(record); return; }
for (int i = 0; i < s.size(); ++i) { if (!used[i]) { if (i != 0 && s[i] == s[i-1] && used[i-1] == false) continue; used[i] = true; record.push_back(s[i]); backtrack(s, record); record.pop_back(); used[i] = false; } } } };
|
| class Solution { public: vector<string> Permutation(string str) { vector<string> res; if (str.size() == 0) return res; sort(str.begin(), str.end()); do { res.push_back(str); } while (next_permutation(str.begin(), str.end())); return res; } };
|