301. Remove Invalid Parentheses

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 in s.

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
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值