-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path022_Generate_Parentheses.cpp
More file actions
82 lines (81 loc) · 2.11 KB
/
022_Generate_Parentheses.cpp
File metadata and controls
82 lines (81 loc) · 2.11 KB
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
75
76
77
78
79
80
81
82
#include<iostream>
#include<algorithm>
#include<bitset>
#include<stack>
#include<cmath>
#include<vector>
#include<string>
#include<map>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
class Solution
{
public:
bool isValid(string s)
{
stack<char> mystack;
map<char,char> expect = {
{'1', '0'},
};
while(not s.empty())
{
char a = s[0];
if(a == '1' )
mystack.push(a);
else
{
if( mystack.empty() )
return false;
else
{
char top = mystack.top();
char expect_char = expect[top];
if( a == expect_char)
mystack.pop();
else
return false;
}
}
s = s.substr(1);
}
if( mystack.empty() )
return true;
else
return false;
}
vector<string> generateParenthesis(int n)
{
if( n == 1) return {"()"};
int k = 2*(n -1);
vector<string> res;
for(int i = 0; i < (pow(2,k)-1);i++ )
{
bitset<64> num(i);
size_t num_1 = num.count();
size_t num_0 = k-num_1;
if(num_0 == num_1)
{
string num_str = num.to_string().substr(64-k);
num_str = "1"+num_str+"0";
if(isValid(num_str))
{
replace(num_str.begin(), num_str.end(), '1', '(');
replace(num_str.begin(), num_str.end(), '0', ')');
cout<<i<<"\t"<<num_str<<"\t"<<num_0<<"\t"<<num_1<<endl;
res.push_back(num_str);
}
}
}
return res;
}
};
int main(int argc, char const *argv[])
{
Solution sol;
sol.generateParenthesis(1);
return 0;
}