Leetcode 267. Palindrome Permutation I (Medium) (cpp)
Tag: Backtracking
Difficulty: Medium
/*
267. Palindrome Permutation I (Medium)
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
For example:
Given s = "aabb", return ["abba", "baab"].
Given s = "abc", return [].
Hint:
If a palindromic permutation exists, we just need to generate the first half of the string.
To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
*/
class Solution {
public:
vector<string> generatePalindromes(string s) {
unordered_map<char, int> mapping;
for (char cha : s) {
mapping[cha]++;
}
string str;
string c = "";
bool odd = false;
for (auto i = mapping.begin(); i != mapping.end(); i++) {
if (i->second % 2) {
if (odd) {
return {};
}
c.push_back(i->first);
odd = true;
}
int temp = i->second / 2;
while (temp > 0) {
str += i->first;
temp--;
}
}
vector<string> res;
helper(res, str, 0);
for (int i = 0 ; i < res.size(); i++) {
string temp = res[i];
reverse(temp.begin(), temp.end());
res[i] += c + temp;
}
return res;
}
private:
void helper(vector<string>& res, string& str, int index) {
if (index == str.size()) {
res.push_back(str);
return;
}
set<char> s;
for (int i = index; i < str.size(); i++) {
if (i == index || s.find(str[i]) == s.end()) {
s.insert(str[i]);
swap(str[i], str[index]);
helper(res, str, index + 1);
swap(str[i], str[index]);
}
}
}
};