forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_parentheses.cpp
More file actions
36 lines (30 loc) · 872 Bytes
/
generate_parentheses.cpp
File metadata and controls
36 lines (30 loc) · 872 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
36
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
*/
void solve(int off, int left, int right, string &sol, int n, vector<string> &res) {
if (off == 2 * n) {
res.push_back(sol);
return ;
}
if (left < n) {
sol.push_back('(');
solve(off + 1, left + 1, right, sol, n, res);
sol = sol.substr(0, sol.size() - 1);
}
if (right < left) {
sol.push_back(')');
solve(off + 1, left, right + 1, sol, n, res);
sol = sol.substr(0, sol.size() - 1);
}
}
class Solution {
public:
vector<string> generateParenthesis(int n) {
string sol = "";
vector<string> res;
solve(0, 0, 0, sol, n, res);
return res;
}
};