LeetCode_回溯_困难_301. 删除无效的括号

x33g5p2x  于2022-05-30 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(295)

1.题目

给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。

返回所有可能的结果。答案可以按任意顺序返回。

示例 1:
输入:s = “()())()”
输出:[“(())()”,“()()()”]

示例 2:
输入:s = “(a)())()”
输出:[“(a())()”,“(a)()()”]

示例 3:
输入:s = “)(”
输出:[“”]

提示:
1 <= s.length <= 25
s 由小写英文字母以及括号 ‘(’ 和 ‘)’ 组成
s 中至多含 20 个括号

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-invalid-parentheses

2.思路

(1)回溯
思路参考本题官方题解

3.代码实现(Java)

  1. //思路1————回溯
  2. public class Solution {
  3. //存放所有可能的结果
  4. List<String> res = new ArrayList<String>();
  5. public List<String> removeInvalidParentheses(String s) {
  6. int lremove = 0;
  7. int rremove = 0;
  8. for (int i = 0; i < s.length(); i++) {
  9. if (s.charAt(i) == '(') {
  10. lremove++;
  11. } else if (s.charAt(i) == ')') {
  12. if (lremove == 0) {
  13. rremove++;
  14. } else {
  15. lremove--;
  16. }
  17. }
  18. }
  19. backtrace(s, 0, lremove, rremove);
  20. return res;
  21. }
  22. public void backtrace(String str, int start, int lremove, int rremove) {
  23. if (lremove == 0 && rremove == 0) {
  24. if (isValid(str)) {
  25. res.add(str);
  26. }
  27. return;
  28. }
  29. for (int i = start; i < str.length(); i++) {
  30. if (i != start && str.charAt(i) == str.charAt(i - 1)) {
  31. continue;
  32. }
  33. //剪枝操作:如果剩余的字符无法满足去掉的数量要求,直接返回
  34. if (lremove + rremove > str.length() - i) {
  35. return;
  36. }
  37. //尝试去掉一个左括号
  38. if (lremove > 0 && str.charAt(i) == '(') {
  39. backtrace(str.substring(0, i) + str.substring(i + 1), i, lremove - 1, rremove);;
  40. }
  41. //尝试去掉一个右括号
  42. if (rremove > 0 && str.charAt(i) == ')') {
  43. backtrace(str.substring(0, i) + str.substring(i + 1), i, lremove, rremove - 1);
  44. }
  45. }
  46. }
  47. //判断字符串 str 中的括号是否有效
  48. public boolean isValid(String str) {
  49. int cnt = 0;
  50. for (int i = 0; i < str.length(); i++) {
  51. if (str.charAt(i) == '(') {
  52. cnt++;
  53. } else if (str.charAt(i) == ')') {
  54. cnt--;
  55. if (cnt < 0) {
  56. return false;
  57. }
  58. }
  59. }
  60. return cnt == 0;
  61. }
  62. }

相关文章