-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathremove_invalid_parentheses.cpp
74 lines (70 loc) · 1.97 KB
/
remove_invalid_parentheses.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
This problem is solved using backtracking.
In this problem we will be given string of parenthesis which will open and closing parenthesis.
We will have to remove minimum no. of parenthesis to make the string valid and will print all possible valid strings made by min. removal.
*/
#include <bits/stdc++.h>
using namespace std;
// this function is to find no. of parenthesis to be removed from the string
int minRemoval(string str){
stack<int> s;
for(int i=0;i<str.length();i++){
// if it is a open parentheses then we will always push
if(str[i] == '('){
s.push(str[i]);
}
// if closed parentheses
else if(str[i] == ')'){
// if stack is empty then we will push
if(s.size() == 0){
s.push(str[i]);
}
// if stack top is closed parentheses then we will push
else if(s.top() == ')'){
s.push(str[i]);
}
// if stack top is open parentheses then we will pop
else {
s.pop();
}
}
}
// size left will me the minimum parentheses to be removed to make the string valid
return s.size();
}
void validParentheses(string str, int rm, unordered_set<string> &result){
if(rm == 0){
int remove = minRemoval(str);
if(remove == 0){
result.insert(str);
}
return;
}
for(int i=0;i<str.length();i++){
string left = str.substr(0,i);
string right = str.substr(i+1);
validParentheses(left + right,rm-1,result);
}
}
// driver code
int main() {
// Input the parentheses string
string str;
cin>>str;
unordered_set<string> result;
// no. of parentheses to be removed
int remove = minRemoval(str);
//recursive call
validParentheses(str,remove,result);
for(auto i:result){
cout<<i<<endl;
}
return 0;
}
/*
Input - ()())()
Output -
()()()
()())()
Time Complexity - O(n!)
*/