-
Notifications
You must be signed in to change notification settings - Fork 3
/
301.cpp
44 lines (43 loc) · 1.28 KB
/
301.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
vector<string> res;
void backtracking(string s, int curr, int leftCnt, int rightCnt) {
if (leftCnt == 0 && rightCnt == 0) {
if (isValid(s)) res.push_back(s);
return;
}
for (int i = curr; i < s.size(); ++i) {
if (i > 0 && s[i] == s[i - 1]) continue;
if (s[i] == '(' && leftCnt) {
backtracking(s.substr(0, i) + s.substr(i + 1), i, leftCnt - 1, rightCnt);
}
if (s[i] == ')' && rightCnt) {
backtracking(s.substr(0, i) + s.substr(i + 1), i, leftCnt, rightCnt - 1);
}
}
}
bool isValid(string& s) {
int cnt = 0;
for (auto& c : s) {
if (c == '(') cnt++;
else if (c == ')') {
if (cnt == 0) return false;
cnt--;
}
}
return cnt == 0;
}
vector<string> removeInvalidParentheses(string s) {
int leftCnt = 0;
int rightCnt = 0;
for (auto& c : s) {
if (c == '(') leftCnt++;
else if (c == ')') {
if (leftCnt == 0) rightCnt++;
else leftCnt--;
}
}
backtracking(s, 0, leftCnt, rightCnt);
return res;
}
};