palindrome-permutation-ii Posted on 2018-10-28 Descriptionhttps://leetcode.com/problems/palindrome-permutation-ii/ Solution1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950class Solution {public: vector<string> generatePalindromes(string s) { vector<string> ret; unordered_map<char, int> counter; for (int i = 0; i < s.size(); ++i) { counter[s[i]] += 1; } int singularCount = 0; char singularChar; bool singularFlag = false; for (auto& item : counter) { if (item.second % 2) { singularCount += 1; singularChar = item.first; singularFlag = true; } } if (singularCount > 1) return ret; string cur; if (singularFlag) { cur += singularChar; --counter[singularChar]; } helper(ret, counter, cur, '\n', s.size()); return ret; } void helper(vector<string>& ret, unordered_map<char, int>& counter, string cur, char pre, int lens){ bool flag = false; // mark the end string originStr = cur; for (auto& item : counter) { if (item.second == 0 || item.first == pre) continue; flag = true; int originCount = item.second; // string newStr = item.first + cur + item.first; while(item.second > 0) { cur = item.first + cur + item.first; item.second -= 2; helper(ret, counter, cur, item.first, lens); } item.second = originCount; cur = originStr; } if (cur.size() == lens) ret.push_back(cur); }};