Approach
Depth-first search
For Brace Expansion 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
- 34 lines of Python from the credited upstream file 1096.py.
- 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 def braceExpansionII(self, expression: str) -> list[str]:3 def merge(groups: list[list[str]], group: list[str]) -> None:4 if not groups[-1]:5 groups[-1] = group6 return7 8 groups[-1] = [word1 + word2 for word1 in groups[-1]9 for word2 in group]10 11 def dfs(s: int, e: int) -> list[str]:12 groups = [[]]13 layer = 014 15 for i in range(s, e + 1):16 c = expression[i]17 if c == '{':18 layer += 119 if layer == 1:20 left = i + 121 elif c == '}':22 layer -= 123 if layer == 0:24 group = dfs(left, i - 1)25 merge(groups, group)26 elif c == ',' and layer == 0:27 groups.append([])28 elif layer == 0:29 merge(groups, [c])30 31 return sorted(list({word for group in groups for word in group}))32 33 return dfs(0, len(expression) - 1)34