-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.generate-parentheses.cpp
More file actions
70 lines (67 loc) · 1.69 KB
/
22.generate-parentheses.cpp
File metadata and controls
70 lines (67 loc) · 1.69 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* @lc app=leetcode id=22 lang=cpp
*
* [22] Generate Parentheses
*
* https://leetcode.com/problems/generate-parentheses/description/
*
* algorithms
* Medium (51.03%)
* Likes: 3644
* Dislikes: 212
* Total Accepted: 428.4K
* Total Submissions: 734.3K
* Testcase Example: '3'
*
*
* 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:
*
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
*/
// @lc code=start
class Solution {
public:
void generateParenthesisHelper(int n, std::string buffer, int buffer_index,
int opened_brackets, int unclosed_brackets,
std::vector<string>& return_vector) {
if (buffer_index == buffer.size()) {
return_vector.push_back(buffer);
return;
}
if (opened_brackets < n) {
buffer[buffer_index] = '(';
generateParenthesisHelper(n, buffer, buffer_index + 1,
opened_brackets + 1, unclosed_brackets + 1,
return_vector);
}
if (unclosed_brackets > 0) {
buffer[buffer_index] = ')';
generateParenthesisHelper(n, buffer, buffer_index + 1, opened_brackets,
unclosed_brackets - 1, return_vector);
}
return;
}
vector<string> generateParenthesis(int n) {
std::vector<string> return_vector;
if (!n) {
return return_vector;
}
std::string buffer(n * 2, '\0');
generateParenthesisHelper(n, buffer, 0, 0, 0, return_vector);
return return_vector;
}
};
// @lc code=end