LeetCode 267. Palindrome Permutation II(对称排列)

原题网址:https://leetcode.com/problems/palindrome-permutation-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.

For example:

Given s = "aabb", return ["abba", "baab"].

Given s = "abc", return [].

Hint:

  1. If a palindromic permutation exists, we just need to generate the first half of the string.
  2. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.

方法:深度优先搜索,生成前半段,后半段镜像复制。

public class Solution {
    private void find(char[] chs, char center, int left, int right, char[] palindrome, List results) {
        if (left == right) {
            palindrome[left] = center;
            results.add(new String(palindrome));
            return;
        } else if (left > right) {
            results.add(new String(palindrome));
            return;
        }
        boolean[] used = new boolean[256];
        for(int i=left; i generatePalindromes(String s) {
        List results = new ArrayList<>();
        char[] sa = s.toCharArray();
        int[] f = new int[256];
        for(int i=0; i

used数组每次都要创建比较浪费空间和时间,如果每个深度使用字符从0~255进行循环,则不需要担心重复的问题,就可以通过计数器来维护使用状态。

public class Solution {
    private void find(int[] frequency, int[] used, char center, char[] permutation, int step, List results) {
        if (step == permutation.length/2) {
            if ((permutation.length & 1) == 1) permutation[step++] = center;
            for(int i=0, j=permutation.length-1; i= (frequency[ch]>>1)) continue;
            used[ch] ++;
            permutation[step] = ch;
            find(frequency, used, center, permutation, step+1, results);
            used[ch] --;
        }
    }
    public List generatePalindromes(String s) {
        List results = new ArrayList<>();
        char[] sa = s.toCharArray();
        boolean single = false;
        char center = '\0';
        int[] frequency = new int[256];
        for(int i=0; i

你可能感兴趣的:(对称,排列,深度优先搜索,重复,唯一,组合)