forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0022-generate-parentheses.cpp
31 lines (28 loc) · 857 Bytes
/
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
/*
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)
*/
classSolution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generate(n, 0, 0, "", result);
return result;
}
private:
voidgenerate(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);
}
}
};