LeetCode刷题实战267:回文排列II

算法的重要性,我就很少说了吧,想去大厂,就必需要通过基础知识和业务逻辑面试+算法面试。因此,为了提升你们的算法能力,后续天天带你们作一道算法题,题目就从LeetCode上面选 !今天和你们聊的问题叫作 回文排列II,咱们先来看题面:

 

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.面试

给定一个字符串 s ,返回其经过从新排列组合后全部可能的回文字符串,并去除重复的组合。如不能造成任何回文排列时,则返回一个空列表。

示例

示例 1:
输入: "aabb"
输出: ["abba", "baab"]

示例 2:
输入: "abc"
输出: []

 

 

解题

对字符进行计数,判断可否生成回文串而后把奇数个的1个字符放中间,回溯在字符两侧放一对相同的字符

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;//回溯
        }
      }
    }
};算法

好了,今天的文章就到这里,若是以为有所收获,大家的支持是我最大的动力 。

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

相关文章
相关标签/搜索