![]() |
VOOZH | about |
Given a string str consisting only of lowercase letters and the characters '(' and ')'. Your task is to delete minimum parentheses so that the resulting string is balanced, i.e., every opening parenthesis has a matching closing parenthesis in the correct order, and no extra closing parentheses appear.
Return all distinct strings you can obtain by performing the minimum number of removals.
Examples:
Input: str = "()())()"
Output: "()()()" "(())()"
Explanation: We can remove the closing bracket at index 3 to obtain the balanced string "()()()". Similarly, we can remove the closing bracket at index 1 to obtain the balanced string "(())()".Input: str = "(v)())()"
Output: "(v)()()" "(v())()"
Explanation: The given string is the modified version of first string containing a letter 'v' . As the letters do not differ the parentheses, the solution remains the same.Input: S = ")("
Output: ""
Table of Content
The idea is to remove brackets one by one and check for balance. To remove brackets in a systematic way, we use BFS order. We remove one bracket at a time, check for balance, then remove more brackets and again check in BFS manner. We stop when we find a balanced string.
One important observation about this problem is, we can check the balancing by simply counting opening and closing brackets because we have only one type of brackets. We do not need to use stack to check.
(())() ()()()
We first determine how many opening
(and closing)parentheses are invalid and need to be removed. Then, use a recursive function to explore all ways of removing these parentheses while maintaining balance between open and close brackets. At each step, either skip a parenthesis (if it's invalid) or include it in the current string (if it helps form a valid expression), and continue building the string. Only strings that end with no unmatched parentheses are collected as valid results.
Step-by-step approach to process '())(':
Final result is ["()"]
(())() ()()()