-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathgenerate-parentheses.cpp
More file actions
35 lines (32 loc) · 923 Bytes
/
generate-parentheses.cpp
File metadata and controls
35 lines (32 loc) · 923 Bytes
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
// Time: O(n * (C(2n, n) - C(2n, n - 1))) = Catalan numbers
// Space: O(n)
class Solution {
public:
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
vector<string> generateParenthesis(int n) {
vector<string> result;
string cur;
generateParenthesisHelper(n, n, &cur, &result);
return result;
}
void generateParenthesisHelper(
int left, int right,
string *cur, vector<string> *result) {
if (!left && !right) {
result->emplace_back(*cur);
}
if (left > 0) {
cur->push_back('(');
generateParenthesisHelper(left - 1, right, cur, result);
cur->pop_back();
}
if (left < right) {
cur->push_back(')');
generateParenthesisHelper(left, right - 1, cur, result);
cur->pop_back();
}
}
};