题目

类型:BFS
image.png

解题思路

使用回溯算法,尝试遍历所有可能的去掉非法括号的方案。

首先利用括号匹配的规则求出该字符串 s 中最少需要去掉的左括号的数目 lremove 和右括号的数目 rremove,然后我们尝试在原字符串 s 中去掉 lremove 个左括号和 rremove 个右括号,然后检测剩余的字符串是否合法匹配,如果合法匹配则则认为该字符串为可能的结果,利用回溯算法来尝试搜索所有可能的去除括号的方案。

在进行回溯时可以利用以下的剪枝技巧来增加搜索的效率:

  • 充分利用括号左右匹配的特点(性质),因此设置变量 lcount 和 rcount,分别表示在遍历的过程中已经用到的左括号的个数和右括号的个数,当出现 lcount<rcount 时,则认为当前的字符串已经非法,停止本次搜索。
  • 从字符串中每去掉一个括号,则更新 lremove 或者 rremove,当发现剩余未尝试的字符串的长度小于 lremove+rremove 时,则停止本次搜索。
  • 当 lremove 和 rremove 同时为 0 时,则检测当前的字符串是否合法匹配,如果合法匹配则将其记录下来。

由于记录的字符串可能存在重复,因此需要对重复的结果进行去重,去重的办法有如下两种:

  • 利用哈希表对最终生成的字符串去重。
  • 在每次进行搜索时,如果遇到连续相同的括号我们只需要搜索一次即可,比如当前遇到的字符串为 (((()),去掉前四个左括号中的任意一个,生成的字符串是一样的,均为 ((()),因此在尝试搜索时,只需去掉一个左括号进行下一轮搜索,不需要将前四个左括号都尝试一遍。

代码

  1. class Solution {
  2. private List<String> res = new ArrayList<String>();
  3. public List<String> removeInvalidParentheses(String s) {
  4. int lremove = 0;
  5. int rremove = 0;
  6. for (int i = 0; i < s.length(); i++) {
  7. if (s.charAt(i) == '(') {
  8. lremove++;
  9. } else if (s.charAt(i) == ')') {
  10. if (lremove == 0) {
  11. rremove++;
  12. } else {
  13. lremove--;
  14. }
  15. }
  16. }
  17. helper(s, 0, 0, 0, lremove, rremove);
  18. return res;
  19. }
  20. private void helper(String str, int start, int lcount, int rcount, int lremove, int rremove) {
  21. if (lremove == 0 && rremove == 0) {
  22. if (isValid(str)) {
  23. res.add(str);
  24. }
  25. return;
  26. }
  27. for (int i = start; i < str.length(); i++) {
  28. if (i != start && str.charAt(i) == str.charAt(i - 1)) {
  29. continue;
  30. }
  31. // 如果剩余的字符无法满足去掉的数量要求,直接返回
  32. if (lremove + rremove > str.length() - i) {
  33. return;
  34. }
  35. // 尝试去掉一个左括号
  36. if (lremove > 0 && str.charAt(i) == '(') {
  37. helper(str.substring(0, i) + str.substring(i + 1), i, lcount, rcount, lremove - 1, rremove);
  38. }
  39. // 尝试去掉一个右括号
  40. if (rremove > 0 && str.charAt(i) == ')') {
  41. helper(str.substring(0, i) + str.substring(i + 1), i, lcount, rcount, lremove, rremove - 1);
  42. }
  43. if (str.charAt(i) == ')') {
  44. lcount++;
  45. } else if (str.charAt(i) == ')') {
  46. rcount++;
  47. }
  48. // 当前右括号的数量大于左括号的数量则为非法,直接返回.
  49. if (rcount > lcount) {
  50. break;
  51. }
  52. }
  53. }
  54. private boolean isValid(String str) {
  55. int cnt = 0;
  56. for (int i = 0; i < str.length(); i++) {
  57. if (str.charAt(i) == '(') {
  58. cnt++;
  59. } else if (str.charAt(i) == ')') {
  60. cnt--;
  61. if (cnt < 0) {
  62. return false;
  63. }
  64. }
  65. }
  66. return cnt == 0;
  67. }
  68. }