给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。 返回所有可能的结果。答案可以按 任意顺序 返回

  1. class Solution(object):

  2. def removeInvalidParentheses(self, s):

  3. """

  4. :type s: str

  5. :rtype: List[str]

  6. """

  7. if len(s) == 0:

  8. return [""]

  9. count1 = 0

  10. count2 = 0

  11. for str_num in s:

  12. count1 += (str_num=="(")

  13. if count1 == 0:

  14. count2 += (str_num==")")

  15. else:

  16. count1 -= (str_num==")")

  17. start = 0

  18. res = []

  19. self.DFS(s, start, count1, count2, res)

  20. return res

  21. def DFS(self, s, start, count1, count2, res):

  22. if count1 == 0 and count2 == 0: #一样多

  23. if self.isValid(s):

  24. res.append(s)

  25. return

  26. else:

  27. for i in range(start, len(s)):

  28. if i != start and s[i] == s[i-1]:

  29. continue #重复的只计算一次

  30. elif count1 > 0 and s[i] == "(": #左多

  31. self.DFS(s[:i]+s[i+1:], i, count1-1, count2, res)

  32. elif count2 > 0 and s[i] == ")": #右多

  33. self.DFS(s[:i]+s[i+1:], i, count1, count2-1, res)

  34. def isValid(self, string):

  35. count = 0

  36. for i in range(len(string)):

  37. if string[i] == "(":

  38. count += 1

  39. elif string[i] == ")":

  40. count -= 1

  41. if count < 0:

  42. return False

  43. return count == 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值