-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0301-remove-invalid-parentheses.py
More file actions
47 lines (40 loc) · 1.51 KB
/
0301-remove-invalid-parentheses.py
File metadata and controls
47 lines (40 loc) · 1.51 KB
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
38
39
40
41
42
43
44
45
46
47
# time complexity: O(2^n * n)
# space complexity: O(2^n * n)
from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def isValid(s):
stack = []
for i in range(len(s)):
if (s[i] == '('):
stack.append((i, '('))
elif (s[i] == ')'):
if (stack and stack[-1][1] == '('):
stack.pop()
else:
stack.append((i, ')'))
return len(stack) == 0, stack
def backtrack(s, left, right):
visited.add(s)
if left == 0 and right == 0 and isValid(s)[0]:
result.append(s)
for i, char in enumerate(s):
if char != '(' and char != ')':
continue
if (char == '(' and left == 0) or (char == ')' and right == 0):
continue
if s[:i] + s[i+1:] not in visited:
backtrack(s[:i] + s[i+1:], left -
(char == '('), right - (char == ')'))
stack = isValid(s)[1]
leftCount = sum([1 for val in stack if val[1] == "("])
rightCount = len(stack) - leftCount
result, visited = [], set()
backtrack(s, leftCount, rightCount)
return result
s = "()())()"
print(Solution().removeInvalidParentheses(s))
s = "(a)())()"
print(Solution().removeInvalidParentheses(s))
s = ")("
print(Solution().removeInvalidParentheses(s))