-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0022-generate-parentheses.cpp
66 lines (60 loc) · 1.85 KB
/
0022-generate-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
/*
Given n pairs of parentheses, generate all combos of well-formed parentheses
Ex. n = 3 -> ["((()))","(()())","(())()","()(())","()()()"], n = 1 -> ["()"]
Backtracking, keep valid, favor trying opens, then try closes if still valid
Time: O(2^n)
Space: O(n)
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generate(n, 0, 0, "", result);
return result;
}
private:
void generate(int n, int open, int close, string str, vector<string>& result) {
if (open == n && close == n) {
result.push_back(str);
return;
}
if (open < n) {
generate(n, open + 1, close, str + '(', result);
}
if (open > close) {
generate(n, open, close + 1, str + ')', result);
}
}
};
/*
Using a single stack without recursion
Time: O(2^n)
Space: O(n)
*/
class Solution {
public:
vector<string> generateParenthesis(int n) {
stack<vector<string>> stk;
vector<string> result;
stk.push({"(", "1", "0"}); // {string, left_count, right_count}
while (!stk.empty()) {
for (int i = 0; i < stk.size(); i++) {
vector<string> item = stk.top();
stk.pop();
int left = stoi(item[1]), right = stoi(item[2]);
if (left == n && right == n) {
result.push_back(item[0]);
continue;
}
if (left < n) {
stk.push({item[0] + "(", to_string(++left), to_string(right)});
left--; // reverse left count
}
if (left > right) {
stk.push({item[0] + ")", to_string(left), to_string(++right)});
}
}
}
return result;
}
};