forked from tiationg-kho/leetcode-pattern-500
-
Notifications
You must be signed in to change notification settings - Fork 0
/
301-remove-invalid-parentheses.py
37 lines (33 loc) · 1.09 KB
/
301-remove-invalid-parentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from collections import deque
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def valid(s):
balance = 0
for c in s:
if c == '(':
balance += 1
elif c == ')':
balance -= 1
if balance < 0:
return False
return balance == 0
queue = deque([s])
res = []
while queue:
length = len(queue)
next_queue = set()
for _ in range(length):
string = queue.popleft()
if valid(string):
res.append(string)
continue
for i, c in enumerate(string):
if c in '()':
next_queue.add(string[: i] + string[i + 1:])
if res:
break
queue.extend(next_queue)
return res
# time O(n * 2**n)
# space O(n * C(2/n, n)), due to the max number of combinations in i round
# using graph and bfs with hashset as queue