Problems: https://leetcode.com/problems/remove-invalid-parentheses/
Solution:
class Solution {
public List<String> removeInvalidParentheses(String s) {
char[] arr = s.toCharArray();
int left = 0, right = 0;
// calculate '(' and ')' needed to be deleted
for(char c : arr) {
if(c == '(') {
left++;
}
if(c == ')') {
if(left != 0) {
left--;
} else {
right++;
}
}
}
ArrayList<String> ans = new ArrayList<>();
dfs(s, 0, left, right, ans);
return ans;
}
public boolean isValid(String str) {
char[] c = str.toCharArray();
int count = 0;
for(char ch : c) {
if(ch == '(') {
count++;
} else if (ch == ')') {
count--;
}
if (count < 0) {
return false; // right appears before left
}
}
return count == 0;
}
public void dfs(String s, int start, int l, int r, ArrayList<String> ans) {
// if valid, add to ans
if (isValid(s)) {
ans.add(s);
return;
}
for (int i = start; i < s.length(); i++) {
// only consider the first paranthes if repeated
if(i != start && s.charAt(i) == s.charAt(i-1)) {
continue;
}
if(s.charAt(i) == '(' || s.charAt(i) == ')') {
String copy = s.substring(0,i) + s.substring(i+1, s.length());
if(r > 0 && s.charAt(i) == ')') {
dfs(copy, i, l, r-1, ans);
}
if(l > 0 && s.charAt(i) == '(') {
dfs(copy, i, l-1, r, ans);
}
}
}
}
}
参考: https://www.youtube.com/watch?v=2k_rS_u6EBk