|
| 1 | +//https://www.lintcode.com/problem/palindrome-permutation-ii/description |
| 2 | +class Solution { |
| 3 | +public: |
| 4 | + /** |
| 5 | + * @param s: the given string |
| 6 | + * @return: all the palindromic permutations (without duplicates) of it |
| 7 | + */ |
| 8 | + vector<char> numss; |
| 9 | + vector<string> global_ans; |
| 10 | + bool isOdd; |
| 11 | + char oddChar; |
| 12 | + |
| 13 | + bool canPerm(string &str) { |
| 14 | + // write your code here |
| 15 | + int n = str.size(); |
| 16 | + map<char,int> mp; |
| 17 | + |
| 18 | + for(auto x: str) |
| 19 | + mp[x]++; |
| 20 | + |
| 21 | + int odd = 0; |
| 22 | + for(auto pp: mp){ |
| 23 | + if(pp.second & 1){ |
| 24 | + odd++; |
| 25 | + isOdd = true; |
| 26 | + oddChar = pp.first; |
| 27 | + } |
| 28 | + if(odd > 1) |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + |
| 33 | + for(auto pp: mp){ |
| 34 | + int k = pp.second; |
| 35 | + k/= 2; |
| 36 | + while(k--){ |
| 37 | + numss.push_back(pp.first); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + void solve(int idx, vector<int>& used, vector<char>& nums, vector<char>& vec){ |
| 45 | + int n = nums.size(); |
| 46 | + // base |
| 47 | + if(idx == n){ |
| 48 | + string str = ""; |
| 49 | + for(int i = 0; i < n; i++){ |
| 50 | + str += vec[i]; |
| 51 | + } |
| 52 | + |
| 53 | + if(isOdd) |
| 54 | + str += oddChar; |
| 55 | + |
| 56 | + for(int i = n-1; i >= 0; i--){ |
| 57 | + str += vec[i]; |
| 58 | + } |
| 59 | + global_ans.push_back(str); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + // main |
| 64 | + // _ |
| 65 | + for(int i = 0; i < n; i++){ |
| 66 | + if(used[i]) |
| 67 | + continue; |
| 68 | + |
| 69 | + if (i > 0 and nums[i-1] == nums[i] and !used[i-1]) |
| 70 | + continue; |
| 71 | + // dups |
| 72 | + |
| 73 | + used[i] = true; |
| 74 | + vec.push_back(nums[i]); |
| 75 | + solve(idx + 1, used, nums, vec); |
| 76 | + |
| 77 | + vec.pop_back(); |
| 78 | + used[i] = false; |
| 79 | + |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + vector<string> permuteUnique(vector<char>& nums) { |
| 84 | + // _ _ _ |
| 85 | + // ^ |
| 86 | + |
| 87 | + int idx = 0; |
| 88 | + int n = nums.size(); |
| 89 | + // sort(nums.begin(), nums.end()); |
| 90 | + |
| 91 | + vector<int> used(n, 0);// bool |
| 92 | + vector<char> vec; |
| 93 | + solve(idx, used, nums, vec); |
| 94 | + |
| 95 | + return global_ans; |
| 96 | + } |
| 97 | + |
| 98 | + vector<string> generatePalindromes(string &str) { |
| 99 | + // write your code here |
| 100 | + isOdd = false; |
| 101 | + if(!canPerm(str)) |
| 102 | + return {}; |
| 103 | + |
| 104 | + //2. generate all unique perms of first half |
| 105 | + for(auto x: numss) |
| 106 | + cout << x << endl; |
| 107 | + |
| 108 | + return permuteUnique(numss); |
| 109 | + } |
| 110 | +}; |
0 commit comments