Problem
You are given a string s
representing a list of words. Each letter in the word has one or more options.
- If there is one option, the letter is represented as is.
- If there is more than one option, then curly braces delimit the options. For example,
"{a,b,c}"
represents options["a", "b", "c"]
.
For example, if s = "a{b,c}"
, the first character is always 'a'
, but the second character can be 'b'
or 'c'
. The original list is ["ab", "ac"]
.
Return all words that can be formed in this manner, sorted in lexicographical order.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Backtracking
The problem aims to generate all possible combination strings. Upon encountering a {
, combinations are formed using the given options, then the process continues from the character following }
. For regular letters, the next character in the string is processed directly. Finally, the resulting combinations are sorted in ascending lexicographical order.
This problem is close to Letter Combinations of a Phone Number
Here is the approach:
- Parse the given string
s
using a loop:- If a character is not enclosed in
{}
, treat it as a single option (e.g.,'a'
becomes['a']
). - If a character is enclosed in
{}
, extract all options (e.g.,"{b,c}"
becomes['b', 'c']
).
- If a character is not enclosed in
- Use backtracking to generate all possible combinations of words:
- Start at the first position and choose an option for each component.
- Recursively combine options from subsequent components.
- After generating all possible combinations, sort the resultant list of words lexicographically.
Approach 1 - With Treeset
|
|
Without Treeset
|
|
Complexity
- ⏰ Time complexity:
O(n + k^m + p log(p))
Parsing the string requires one scan:O(n)
, wheren
is the length of the string. Backtracking generates all combinations, which takesO(k^m)
, wherem
is the number of components (letters or sets of options) andk
is the maximum number of options per component. Sorting the results requiresO(p log(p))
, wherep
is the number of generated words. Overall: O(n + k^m + p log(p)). - 🧺 Space complexity:
O(m * k + p)
. The storage for options usesO(m * k)
. The recursive call stack uses up toO(m)
additional memory, and the result list takesO(p)
space.