LC301 - Remove Invalid Parentheses
Problem
Given a string s
that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.
Example
Example 1:
Input: s = "()())()"
Output: ["(())()","()()()"]
Example 2:
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
Example 3:
Input: s = ")("
Output: [""]
Constraints:
1 <= s.length <= 25
s
consists of lowercase English letters and parentheses'('
and')'
.There will be at most
20
parentheses ins
.
Solution
Use a BFS to explore removal of every parenthesis from the string. If the resulting string is valid, add to result set. Use a set to keep track of visited strings to avoid redundancy. Once a valid string is found, exit the loop as it is guaranteed to have the minimum number. Complexity is T(O(2^n)), S(O(2^n)).
Last updated