-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.cpp
More file actions
36 lines (33 loc) · 935 Bytes
/
22.cpp
File metadata and controls
36 lines (33 loc) · 935 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
// this is just a depth-first search
class Solution {
private:
void backtrack(int n, string& cur, int open, int close,
vector<string>& out) {
if ((open == n) && (close == n)) {
// valid string
out.push_back(cur);
}
if (open < n) {
cur.push_back('(');
backtrack(n, cur, open+1, close, out);
cur.pop_back();
}
if (close < open) {
cur.push_back(')');
backtrack(n, cur, open, close+1, out);
cur.pop_back();
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string cur;
cur.reserve(2*n);
backtrack(n, cur, 0, 0, result);
return result;
}
};
// grammar
// S -> S S
// P -> ( P )
// P -> empty