給定一個字符串 s ,返回其經過從新排列組合後全部可能的迴文字符串,並去除重複的組合。如不能造成任何迴文排列時,則返回一個空列表。
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.面試
class Solution {
vector<string> ans;
int n;
public:
vector<string> generatePalindromes(string s) {
vector<int> count(128,0);
n = s.size();
for(char ch : s)
count[ch]++;
int odd = 0, idx;
for(int i = 0; i < 128; ++i)
{
if(count[i]&1)
{
odd++;
idx = i;
}
if(odd > 1)
return {};
}
s = odd ? string(1, idx) : "";
odd ? count[idx]-- : 0;//奇數的字符-1
dfs(count,s);
return ans;
}
void dfs(vector<int>& count, string s)
{
if(s.size()==n)
{
ans.push_back(s);//長度夠了返回
return;
}
for(int i = 0; i < 128; ++i)
{
if(count[i])
{
count[i] -= 2;//兩側加上相同字符,仍是迴文
dfs(count, char(i)+s+char(i));
count[i] += 2;//回溯
}
}
}
};算法