301. Remove Invalid Parentheses
https://leetcode.com/problems/remove-invalid-parentheses/description/
Thoughts
Code
/*
* @lc app=leetcode id=301 lang=cpp
*
* [301] Remove Invalid Parentheses
*/
// @lc code=start
class Solution {
public:
void dfs(string s, int pos, int last, vector<string> &res, vector<char> p) {
int sum = 0;
for (int i = pos; i < s.length(); ++i) {
if (s[i] == p[0]) ++sum;
else if (s[i] == p[1]) {
--sum;
if (sum >= 0) continue;
for (int j = last; j <= i; ++j) {
if (s[j] == p[1] && (j == last || s[j - 1] != p[1])) {
dfs(s.substr(0, j) + s.substr(j + 1), i, j, res, p);
}
}
return;
}
}
if (p[0] == '(' && sum > 0) {
reverse(s.begin(), s.end());
return dfs(s, 0, 0, res, {')', '('});
}
if (p[0] == ')') reverse(s.begin(), s.end());
res.push_back(s);
}
vector<string> removeInvalidParentheses(string s) {
vector<string> res;
dfs(s, 0, 0, res, {'(', ')'});
return res;
}
};
// @lc code=end
Analysis
Last updated