File tree Expand file tree Collapse file tree 2 files changed +87
-0
lines changed
0301-remove-invalid-parentheses Expand file tree Collapse file tree 2 files changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ <p >Given a string <code >s</code > that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p >
2+
3+ <p >Return <em >a list of <strong >unique strings</strong > that are valid with the minimum number of removals</em >. You may return the answer in <strong >any order</strong >.</p >
4+
5+ <p >  ; </p >
6+ <p ><strong class =" example " >Example 1:</strong ></p >
7+
8+ <pre >
9+ <strong >Input:</strong > s = " ; ()())()" ;
10+ <strong >Output:</strong > [" ; (())()" ; ," ; ()()()" ; ]
11+ </pre >
12+
13+ <p ><strong class =" example " >Example 2:</strong ></p >
14+
15+ <pre >
16+ <strong >Input:</strong > s = " ; (a)())()" ;
17+ <strong >Output:</strong > [" ; (a())()" ; ," ; (a)()()" ; ]
18+ </pre >
19+
20+ <p ><strong class =" example " >Example 3:</strong ></p >
21+
22+ <pre >
23+ <strong >Input:</strong > s = " ; )(" ;
24+ <strong >Output:</strong > [" ;" ; ]
25+ </pre >
26+
27+ <p >  ; </p >
28+ <p ><strong >Constraints:</strong ></p >
29+
30+ <ul >
31+ <li><code>1 <= s.length <= 25</code></li>
32+ <li><code>s</code> consists of lowercase English letters and parentheses <code>'('</code> and <code>')'</code>.</li>
33+ <li>There will be at most <code>20</code> parentheses in <code>s</code>.</li>
34+ </ul >
Original file line number Diff line number Diff line change 1+ # Approach: Backtracking
2+
3+ # Time: O(2^n)
4+ # Space: O(n)
5+
6+ class Solution :
7+ def removeInvalidParentheses (self , s : str ) -> List [str ]:
8+ def isValid (s ):
9+ count = 0
10+ for char in s :
11+ if char == '(' :
12+ count += 1
13+ elif char == ')' :
14+ count -= 1
15+ if count < 0 :
16+ return False
17+ return count == 0
18+
19+ # Use backtracking to try different combinations of removals
20+ def backtrack (s , start , left_count , right_count ):
21+ if left_count == 0 and right_count == 0 :
22+ if isValid (s ):
23+ result .add (s )
24+ return
25+
26+ for i in range (start , len (s )):
27+ # Skip duplicates (Optimization)
28+ if i > start and s [i ] == s [i - 1 ]:
29+ continue
30+
31+ # Try removing left parenthesis
32+ if left_count > 0 and s [i ] == '(' :
33+ backtrack (s [:i ] + s [i + 1 :], i , left_count - 1 , right_count )
34+
35+ # Try removing right parenthesis
36+ if right_count > 0 and s [i ] == ')' :
37+ backtrack (s [:i ] + s [i + 1 :], i , left_count , right_count - 1 )
38+
39+ # Count invalid parentheses
40+ left = right = 0
41+ for char in s :
42+ if char == '(' :
43+ left += 1
44+ elif char == ')' :
45+ if left == 0 :
46+ right += 1
47+ else :
48+ left -= 1
49+
50+ result = set ()
51+ backtrack (s , 0 , left , right )
52+ return list (result )
53+
You can’t perform that action at this time.
0 commit comments