class Solution {
public:
unordered_set<string> valid;
void recurse(string s, int index, int leftCount, int rightCount, int leftRem,int rightRem, string str) {
if (index == s.size()) {
if (leftRem == 0 && rightRem == 0)
valid.insert(str);
}
else {
char c = s[index];
//先不要当前字符
if (c == '(' && leftRem > 0)
recurse(s, index + 1, leftCount, rightCount, leftRem - 1, rightRem, str);
else if (c == ')' && rightRem > 0)
recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem - 1, str);
//加上当前字符
str += c;
if (c != '(' && c != ')') //如果不是括号,则直接加
recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem, str);
else if (c == '(')//加左括号
recurse(s, index + 1, leftCount + 1, rightCount, leftRem, rightRem, str);
else if (rightCount < leftCount)//只在右括号比zuo括号少时,才加右括号
recurse(s, index + 1, leftCount, rightCount + 1, leftRem, rightRem, str);
str.pop_back();//删掉当前字符,回溯
}
}
vector<string> removeInvalidParentheses(string s) {
//计算出冗余的左括号和右括号数量
int left = 0, right = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(')
++left;
else if (s[i] == ')') {
if (left == 0)
++right;
else
--left;
}
}
recurse(s, 0, 0, 0, left, right, "");
return vector<string>(valid.begin(), valid.end());
}
};
301. 删除无效的括号/C++
最新推荐文章于 2023-06-04 22:00:02 发布