forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.h
34 lines (31 loc) · 1.01 KB
/
GenerateParentheses.h
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
/*
Author: Annie Kim, [email protected]
Date: May 17, 2013
Update: Jul 20, 2013
Problem: Generate Parentheses
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_22
Notes:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution: Place n left '(' and n right ')'.
Cannot place ')' if there are no enough matching '('.
*/
class Solution {
public:
vector<string> res;
vector<string> generateParenthesis(int n) {
res.clear();
generateParenthesisRe(n, n, "");
return res;
}
void generateParenthesisRe(int left, int right, string s) {
if (left == 0 && right == 0)
res.push_back(s);
if (left > 0)
generateParenthesisRe(left - 1, right, s + "(");
if (right > left)
generateParenthesisRe(left, right - 1, s + ")");
}
};