给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
返回所有可能的结果。答案可以按 任意顺序 返回。
示例 1:
输入:s = "()())()"
输出:["(())()","()()()"]
示例 2:
输入:s = "(a)())()"
输出:["(a())()","(a)()()"]
示例 3:
输入:s = ")("
输出:[""]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-invalid-parentheses
题目思路:
1、首先满足左右括号的数量一致
2、需要对左右括号数量进行计数,判断需要删除最少的括号
3、对需要删除的括号暴力遍历然后进行判断
优化思路:
1、对遍历进行减支的操作
2、在对每个字符遍历的同时,去除字符(该字符为左右括号)然后进行递归判断去除结果直到需要删除最少括号的结果为0
3、由于遍历顺序是顺序的,所以左括号一定大于右括号(减支)
得到结果:
删除最小括号后的字符串是否合法,然后放入list
class Solution {
public List<String> res = new ArrayList<String>();
public List<String> removeInvalidParentheses(String s) {
int leftNum = 0;
int rightNum = 0;
int sum = 0;
int[] arr = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
if (a == '(') {
++leftNum;
}
if(a == ')') {
if(leftNum == 0)
++rightNum;
else
--leftNum;
}
}
helper(s,0,0,0,leftNum,rightNum);
return res;
}
public void helper(String str, int start, int lcount, int rcount, int lremove, int rremove) {
if (lremove == 0 && rremove == 0) {
if (isInvalid(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;
}
}
}
public static boolean isInvalid(String s){
int cnt = 0;
for(int i = 0;i < s.length();i++)
{
char a = s.charAt(i);
if (a == '(') {
cnt++;
}
else if(a == ')') {
cnt--;
}
if(cnt < 0)
{
return false;
}
}
return true;
}
}