题目链接:https://leetcode.cn/problems/remove-invalid-parentheses/
难度:困难

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

题解

  1. class Solution:
  2. def removeInvalidParentheses(self, s: str) -> List[str]:
  3. ret = []
  4. l, r = 0, 0
  5. for c in s:
  6. if c == '(':
  7. l += 1
  8. elif c == ')':
  9. if l == 0:
  10. r += 1
  11. else:
  12. l -= 1
  13. def isValid(str):
  14. cnt = 0
  15. for c in str:
  16. if c == '(':
  17. cnt += 1
  18. elif c == ')':
  19. cnt -= 1
  20. if cnt < 0:
  21. return False
  22. return cnt == 0
  23. def helper(s, start, l, r):
  24. if l == 0 and r == 0:
  25. if isValid(s):
  26. ret.append(s)
  27. return
  28. for i in range(start, len(s)):
  29. if i > start and s[i] == s[i - 1]:
  30. continue
  31. if l + r > len(s) - i:
  32. break
  33. if l > 0 and s[i] == '(':
  34. helper(s[:i] + s[i + 1:], i, l - 1, r);
  35. if r > 0 and s[i] == ')':
  36. helper(s[:i] + s[i + 1:], i, l, r - 1);
  37. helper(s, 0, l, r)
  38. return ret