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=

相關文章
相關標籤/搜索