Leetcode 267. Palindrome Permutation I (Medium) (cpp)

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]);
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值