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.

Example 1:

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

Example 2:

Input: "abc"
Output: []

题解:

先判断是否palindrome, 若不是返回空的res.

若是,先判断是否有一个奇数位,若有,改char放中间. 然后两边分别加.

Note: check to find single char after updating the map.

Don't forget to minus its count by 1 after appending it to item.

Time Complexity: O(2^n). n = s.length().

Space: O(n). stack space.

AC Java:

 1 class Solution {
 2     public List<String> generatePalindromes(String s) {
 3         List<String> res = new ArrayList<>();
 4         if(s == null || s.length() == 0){
 5             return res;
 6         }
 7         
 8         int [] count = new int[256];
 9         int n = s.length();
10         int po = -1;
11         for(int i = 0; i<n; i++){
12             count[s.charAt(i)]++;
13         }
14         
15         int oneCount = 0;
16         for(int i = 0; i<256; i++){
17             oneCount += count[i]%2;
18             
19             if(count[i]%2 == 1){
20                 po = i;
21             }
22         }
23         
24         if(oneCount > 1){
25             return res;
26         }
27         
28         String init = "";
29         if(po != -1){
30             init += (char)po;
31             count[po]--;
32         }
33         
34         dfs(count, init, n, res);
35         return res;
36     }
37     
38     private void dfs(int [] count, String cur, int n, List<String> res){
39         if(cur.length() == n){
40             res.add(cur);
41             return;
42         }
43         
44         for(int i = 0; i<count.length; i++){
45             if(count[i] > 0){
46                 count[i] -= 2;
47                 dfs(count, (char)i+cur+(char)i, n, res);
48                 count[i] += 2;
49             }
50         }
51     }
52 }

Palindrome Permutation相似. 

posted @ 2016-03-11 13:51  Dylan_Java_NYC  阅读(519)  评论(0编辑  收藏  举报