Leetcode 267 Palindrome Permutaion II

  1. Palindrome Permutation II (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.

Example :
Input: "aabb"
Output: ["abba", "baab"]
Example 2:

Input: "abc"
Output: []

这道题其实就是list all permutation的一个变种,all permutation用到的就是dfs,其中dfs中每一层在这里定义的就是:第i个位置。所以,每一层,从i到最后每一个元素,如果该元素没有在i这个位置上“坐”过,那么swap到i上坐一坐,Set记录,然后跳到下一层,记得从下一层的递归中跳回时要再swap回去,因为如果不恢复,那么就会递归跳回到上一层,但上一层的假设基础是swap前的序列,不恢复会使结果出错。
有了permutation,剩下的就是找到string的一般,所有元素的频率module2,如果有哪一个元素只出现过一次,证明是放在中间的那个,该元素不参加permutation。

public List generatePalindromes(String s) {
    int odd = 0;
    String mid = "";
    List res = new ArrayList<>();
    List list = new ArrayList<>();
    Map map = new HashMap<>();

    // step 1. build character count map and count odds
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);
        odd += map.get(c) % 2 != 0 ? 1 : -1;
    }

    // cannot form any palindromic string
    if (odd > 1) return res;

    // step 2. add half count of each character to list
    for (Map.Entry entry : map.entrySet()) {
        char key = entry.getKey();
        int val = entry.getValue();

        if (val % 2 != 0) mid += key;

        for (int i = 0; i < val / 2; i++) list.add(key);
    }

    // step 3. generate all the permutations
    getPerm(list, mid, new boolean[list.size()], new StringBuilder(), res);

    return res;
}

// generate all unique permutation from list
void getPerm(List list, String mid, boolean[] used, StringBuilder sb, List res) {
    if (sb.length() == list.size()) {
        // form the palindromic string
        res.add(sb.toString() + mid + sb.reverse().toString());
        sb.reverse();
        return;
    }

    for (int i = 0; i < list.size(); i++) {
        // avoid duplication
        if (i > 0 && list.get(i) == list.get(i - 1) && !used[i - 1]) continue;

        if (!used[i]) {
            used[i] = true; sb.append(list.get(i));
            // recursion
            getPerm(list, mid, used, sb, res);
            // backtracking
            used[i] = false; sb.deleteCharAt(sb.length() - 1);
        }
    }
}

你可能感兴趣的:(Leetcode 267 Palindrome Permutaion II)