题目
类型:BFS
解题思路
使用回溯算法,尝试遍历所有可能的去掉非法括号的方案。
首先利用括号匹配的规则求出该字符串 s 中最少需要去掉的左括号的数目 lremove 和右括号的数目 rremove,然后我们尝试在原字符串 s 中去掉 lremove 个左括号和 rremove 个右括号,然后检测剩余的字符串是否合法匹配,如果合法匹配则则认为该字符串为可能的结果,利用回溯算法来尝试搜索所有可能的去除括号的方案。
在进行回溯时可以利用以下的剪枝技巧来增加搜索的效率:
- 充分利用括号左右匹配的特点(性质),因此设置变量 lcount 和 rcount,分别表示在遍历的过程中已经用到的左括号的个数和右括号的个数,当出现 lcount<rcount 时,则认为当前的字符串已经非法,停止本次搜索。
- 从字符串中每去掉一个括号,则更新 lremove 或者 rremove,当发现剩余未尝试的字符串的长度小于 lremove+rremove 时,则停止本次搜索。
- 当 lremove 和 rremove 同时为 0 时,则检测当前的字符串是否合法匹配,如果合法匹配则将其记录下来。
由于记录的字符串可能存在重复,因此需要对重复的结果进行去重,去重的办法有如下两种:
- 利用哈希表对最终生成的字符串去重。
- 在每次进行搜索时,如果遇到连续相同的括号我们只需要搜索一次即可,比如当前遇到的字符串为
(((())
,去掉前四个左括号中的任意一个,生成的字符串是一样的,均为((())
,因此在尝试搜索时,只需去掉一个左括号进行下一轮搜索,不需要将前四个左括号都尝试一遍。
代码
class Solution {
private List<String> res = new ArrayList<String>();
public List<String> removeInvalidParentheses(String s) {
int lremove = 0;
int rremove = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
lremove++;
} else if (s.charAt(i) == ')') {
if (lremove == 0) {
rremove++;
} else {
lremove--;
}
}
}
helper(s, 0, 0, 0, lremove, rremove);
return res;
}
private void helper(String str, int start, int lcount, int rcount, int lremove, int rremove) {
if (lremove == 0 && rremove == 0) {
if (isValid(str)) {
res.add(str);
}
return;
}
for (int i = start; i < str.length(); i++) {
if (i != start && str.charAt(i) == str.charAt(i - 1)) {
continue;
}
// 如果剩余的字符无法满足去掉的数量要求,直接返回
if (lremove + rremove > str.length() - i) {
return;
}
// 尝试去掉一个左括号
if (lremove > 0 && str.charAt(i) == '(') {
helper(str.substring(0, i) + str.substring(i + 1), i, lcount, rcount, lremove - 1, rremove);
}
// 尝试去掉一个右括号
if (rremove > 0 && str.charAt(i) == ')') {
helper(str.substring(0, i) + str.substring(i + 1), i, lcount, rcount, lremove, rremove - 1);
}
if (str.charAt(i) == ')') {
lcount++;
} else if (str.charAt(i) == ')') {
rcount++;
}
// 当前右括号的数量大于左括号的数量则为非法,直接返回.
if (rcount > lcount) {
break;
}
}
}
private boolean isValid(String str) {
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
cnt++;
} else if (str.charAt(i) == ')') {
cnt--;
if (cnt < 0) {
return false;
}
}
}
return cnt == 0;
}
}