Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Example 1:
Input: "()())()" Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()" Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
Approach #1: C++.
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
int l = 0;
int r = 0;
// calculate the mismatch parentheses.
for (char c : s) {
l += (c == '(');
if (l == 0) {
r += (c == ')');
} else {
l -= (c == ')');
}
}
vector<string> ans;
dfs(s, 0, l, r, ans);
return ans;
}
private:
bool isValid(string& s) {
int count = 0;
for (char c : s) {
if (c == '(') count++;
if (c == ')') count--;
if (count < 0) return false;
}
return count == 0;
}
void dfs(string s, int start, int l, int r, vector<string>& ans) {
if (l == 0 && r == 0) {
if (isValid(s)) // judge the string is valid.
ans.push_back(s);
return;
}
for (int i = start; i < s.length(); ++i) {
if (i != start && s[i] == s[i-1]) continue;
// s[i] is '(' or ')'
if (s[i] == '(' || s[i] == ')') {
string curr = s;
curr.erase(i, 1);
if (r > 0) dfs(curr, i, l, r-1, ans);
else if (l > 0) dfs(curr, i, l-1, r, ans);
}
}
}
};
Analysis:
step1: compute min number of '(' and ')' to remove, unbalanced ')' + unblanced '('
step2: try all possible ways to remove r '(' and l ')'. Remove '(' first to make prefix valid.
step3: when r == 0 and l == 0, judging the string is or not fulfiled conditions.