-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.generate-parentheses.cpp
More file actions
57 lines (48 loc) · 1.26 KB
/
22.generate-parentheses.cpp
File metadata and controls
57 lines (48 loc) · 1.26 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
/*
* @lc app=leetcode id=22 lang=cpp
*
* [22] Generate Parentheses
*/
// @lc code=start
class Solution {
public:
vector<string> generateParenthesis(int n) {
if(n == 1) return {"()"};
int open = 0;
int closed = 0;
string cur = "";
vector<string> result;
while(cur.size() == 0 || cur[0] != ')') {
while(open < n) {
cur += "(";
open++;
}
while(closed < open) {
cur += ")";
closed++;
}
result.push_back(cur);
int index = cur.size() - 1;
bool foundReplacement = false;
while(index >= 0 && !foundReplacement) {
char par = cur[index];
cur = cur.erase(index, 1);
index--;
if(par == '(') {
open--;
if(open > closed) {
cur += ")";
closed++;
foundReplacement = true;
}
}
else {
closed--;
}
}
if(!foundReplacement) break;
}
return result;
}
};
// @lc code=end