-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc-301.cpp
46 lines (40 loc) · 1.58 KB
/
lc-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
45
46
class Solution {
public:
void removeParenUtil(const string & s,
string strSoFar,
int index, int numLeftSeen, int numRightSeen,
vector<string> & output, set<string> & oset){
if (index == s.length()){
if (numLeftSeen == numRightSeen &&
oset.find(strSoFar) == oset.end()) {
oset.insert(strSoFar);
output.push_back(strSoFar);
}
return;
}
char ch = s[index];
if (ch != ')') {
if (ch == '(') {
removeParenUtil(s, strSoFar+ch, index+1, numLeftSeen+1, numRightSeen, output, oset);
removeParenUtil(s, strSoFar, index+1, numLeftSeen+1, numRightSeen, output, oset);
} else {
removeParenUtil(s, strSoFar+ch, index+1, numLeftSeen, numRightSeen, output, oset);
}
} else {
//ch == ')', we have two choices
//1. include
if (numRightSeen < numLeftSeen){
removeParenUtil(s, strSoFar+ch, index+1, numLeftSeen, numRightSeen+1, output, oset);
}
//2. exclude
removeParenUtil(s, strSoFar, index+1, numLeftSeen, numRightSeen, output, oset);
}
return;
}
vector<string> removeInvalidParentheses(string s) {
vector<string> output;
set<string> oset;
removeParenUtil(s, "", 0, 0, 0, output, oset);
return output;
}
};