Approach
Depth-first search
For Palindrome Permutation II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 59 lines of Java from the credited upstream file 267.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> generatePalindromes(String s) {3 int odd = 0;4 Map<Character, Integer> count = new HashMap<>();5 6 for (final char c : s.toCharArray())7 count.merge(c, 1, Integer::sum);8 9 10 for (Map.Entry<Character, Integer> entry : count.entrySet())11 if (entry.getValue() % 2 == 1)12 ++odd;13 14 15 if (odd > 1)16 return new ArrayList<>();17 18 List<String> ans = new ArrayList<>();19 List<Character> candidates = new ArrayList<>();20 StringBuilder mid = new StringBuilder();21 22 23 for (Map.Entry<Character, Integer> entry : count.entrySet()) {24 final char key = entry.getKey();25 final int value = entry.getValue();26 if (value % 2 == 1)27 mid.append(key);28 for (int i = 0; i < value / 2; ++i)29 candidates.add(key);30 }31 32 33 dfs(candidates, mid, new boolean[candidates.size()], new StringBuilder(), ans);34 return ans;35 }36 37 38 private void dfs(List<Character> candidates, StringBuilder mid, boolean[] used, StringBuilder sb,39 List<String> ans) {40 if (sb.length() == candidates.size()) {41 ans.add(sb.toString() + mid + sb.reverse().toString());42 sb.reverse();43 return;44 }45 46 for (int i = 0; i < candidates.size(); ++i) {47 if (used[i])48 continue;49 if (i > 0 && candidates.get(i) == candidates.get(i - 1) && !used[i - 1])50 continue;51 used[i] = true;52 sb.append(candidates.get(i));53 dfs(candidates, mid, used, sb, ans);54 sb.deleteCharAt(sb.length() - 1);55 used[i] = false;56 }57 }58}59