301. Remove Invalid Parentheses
1. Description
Given a string s containing letters and parentheses, delete as few parentheses as possible so that the remaining parentheses are balanced. Keep every letter in its original relative order.
Return all distinct strings obtainable with this minimum number of deletions. The results can appear in any order.
2. Example
Example 1
Input: s = “()())()”
Output: ["(())()","()()()"]
Example 2
Input: s = “(a)())()”
Output: ["(a())()","(a)()()"]
Example 3
Input: s = “)(”
Output: [""]
3. Constraints
- 1 <= s.length <= 25
- Each character is a lowercase English letter, ‘(’ or ‘)’.
- s contains no more than 20 parentheses.
4. Solutions
Backtracking
n = str.size(), p = number of parentheses, k = number of distinct answers
Time complexity: O(n * $2^p$), assuming average-case hash table operations
Space complexity: O(n + n * k), excluding the returned vector but including the deduplication set
| |