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: [""]
这道题参考了LeetCode上的解答:here。为了是我们的程序能够在规定的时间完成,我们右增加了剪枝操作,然后为了能够尽可能减少内存使用,我们使用了类成员变量以较少递归参数。
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
remain = 0;
our = s;
helper(0, 0, "", 0);
vector<string> vRes(res.begin(), res.end());
return vRes;
}
private:
int remain;
set<string> res;
string our;
void helper(int left, int right, string candidate, int index) {
if (index == our.size()) {
if (left == right) {
if (candidate.size() >= remain) {
remain = candidate.size();
if (candidate.size() > remain)
res = set<string>();
res.insert(candidate);
}
}
return;
}
if (left < right) return;
if (left-right > our.size() - index) return;
string newCan = candidate + our[index];
int newIndex = index + 1;
if (our[index] != '(' && our[index] != ')') {
helper(left, right, newCan, newIndex);
}
else {
if (our[index] == '(') {
helper(left + 1, right, newCan, newIndex);
helper(left, right, candidate, newIndex);
}
else {
helper(left, right + 1, newCan, newIndex);
helper(left, right, candidate, newIndex);
}
}
return;
}
};