[LeetCode] Remove Invalid Parentheses

301. Remove Invalid Parentheses

Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.

Return all the possible results. You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
int rm = INT_MAX;
unordered_set<string> cache[26];
void dfs(vector<string>& res, string& s, int i, int removed, string ss, int check) {
if(removed > rm or cache[i].count(ss) or check < 0) return;
cache[i].insert(ss);
if(i == s.length()) {
if(!check) {
if(rm > removed) {
rm = removed;
res.clear();
}
res.push_back(ss);
}
return;
}
dfs(res, s, i + 1, removed, ss + s[i], check + (s[i] == ')' ? -1 : s[i] == '('));
if(s[i] == '(' or s[i] == ')') {
dfs(res, s, i + 1, removed + 1, ss, check);
}
}
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> res;
dfs(res, s, 0, 0, "", 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/remove-invalid-parentheses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.