Approach
Depth-first search
For Generalized Abbreviation, 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
- 37 lines of C++ from the credited upstream file 320.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block 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> generateAbbreviations(string word) {4 vector<string> ans;5 dfs(word, 0, 0, {}, ans);6 return ans;7 }8 9 private:10 void dfs(const string& word, int i, int count, vector<string>&& path,11 vector<string>& ans) {12 if (i == word.length()) {13 ans.push_back(join(path) + getCountString(count));14 return;15 }16 17 18 dfs(word, i + 1, count + 1, std::move(path), ans);19 20 path.push_back(getCountString(count) + word[i]);21 22 dfs(word, i + 1, 0, std::move(path), ans);23 path.pop_back();24 }25 26 string getCountString(int count) {27 return count > 0 ? to_string(count) : "";28 }29 30 string join(const vector<string>& path) {31 string joined;32 for (const string& s : path)33 joined += s;34 return joined;35 };36};37