-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy paths1.cpp
30 lines (30 loc) · 786 Bytes
/
s1.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
// OJ: https://leetcode.com/problems/generate-parentheses/
// Author: github.com/lzl124631x
// Time: O(C(N)) where C(N) is the Nth Catalan number
// Space: O(N)
class Solution {
private:
vector<string> ans;
void generate(int leftCnt, int rightCnt, string &s) {
if (!leftCnt && !rightCnt) {
ans.push_back(s);
return;
}
if (leftCnt) {
s.push_back('(');
generate(leftCnt - 1, rightCnt, s);
s.pop_back();
}
if (rightCnt > leftCnt) {
s.push_back(')');
generate(leftCnt, rightCnt - 1, s);
s.pop_back();
}
}
public:
vector<string> generateParenthesis(int n) {
string s;
generate(n, n, s);
return ans;
}
};