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
- 60 lines of C++ from the credited upstream file 267.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 vector<string> generatePalindromes(string s) {4 int odd = 0;5 unordered_map<char, int> count;6 7 for (const char c : s)8 ++count[c];9 10 11 for (const auto& [_, value] : count)12 if (value % 2 == 1)13 ++odd;14 15 16 if (odd > 1)17 return {};18 19 vector<string> ans;20 vector<char> candidates;21 string mid;22 23 24 for (const auto& [key, value] : count) {25 if (value % 2 == 1)26 mid += key;27 for (int i = 0; i < value / 2; ++i)28 candidates.push_back(key);29 }30 31 32 dfs(candidates, mid, vector<bool>(candidates.size()), "", ans);33 return ans;34 }35 36 private:37 38 void dfs(const vector<char>& candidates, const string& mid,39 vector<bool>&& used, string&& path, vector<string>& ans) {40 if (path.length() == candidates.size()) {41 string secondHalf = path;42 ranges::reverse(secondHalf);43 ans.push_back(path + mid + secondHalf);44 return;45 }46 47 for (int i = 0; i < candidates.size(); ++i) {48 if (used[i])49 continue;50 if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1])51 continue;52 used[i] = true;53 path.push_back(candidates[i]);54 dfs(candidates, mid, std::move(used), std::move(path), ans);55 path.pop_back();56 used[i] = false;57 }58 }59};60