301. Remove Invalid Parentheses
Hard
4495226Add to ListShare
Given a string s
that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
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
.
Accepted
338,492
Submissions
724,647
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
# how many pairs do we need to keep
lft=0
for char in s:
if char == '(':lft+=1
if char == ')':lft-=(lft>0)
total = s.count('(')-lft
ans=set()
def dfs(ind,l,r,built):
if ind==len(s) and l ==0 and r==0:
ans.add(built)
if ind == len(s):
return ans
if s[ind] == "(":
if l>0: dfs(ind+1,l-1,r,built+s[ind])
dfs(ind+1,l,r,built)
elif s[ind] == ")":
if r>0 and l<=r-1:dfs(ind+1,l,r-1,built+s[ind])
dfs(ind+1,l,r,built)
else:
dfs(ind+1,l,r,built+s[ind])
// current index, "("l remaining, ")"r remaining, built string
dfs(0,total,total,"")
return ans