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
- 29 lines of Java from the credited upstream file 320.java.
- The implementation visibly relies on sequence storage.
- No explicit 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> generateAbbreviations(String word) {3 List<String> ans = new ArrayList<>();4 dfs(word, 0, 0, new StringBuilder(), ans);5 return ans;6 }7 8 private void dfs(final String word, int i, int count, StringBuilder sb, List<String> ans) {9 if (i == word.length()) {10 final int length = sb.length();11 ans.add(sb.append(getCountString(count)).toString());12 sb.setLength(length);13 return;14 }15 16 17 dfs(word, i + 1, count + 1, sb, ans);18 19 final int length = sb.length();20 21 dfs(word, i + 1, 0, sb.append(getCountString(count)).append(word.charAt(i)), ans);22 sb.setLength(length);23 }24 25 private String getCountString(int count) {26 return count > 0 ? String.valueOf(count) : "";27 }28}29