22 Generate Parentheses

1. Question

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, givenn= 3, a solution set is:
1
[
2
"((()))",
3
"(()())",
4
"(())()",
5
"()(())",
6
"()()()"
7
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<String> generateParenthesis(int n) {
3
List<String> res = new ArrayList<>();
4
StringBuilder paren = new StringBuilder();
5
getParenthesis(0, 0, n, paren, res);
6
return res;
7
}
8
9
public void getParenthesis(int left, int right, int n, StringBuilder paren, List<String> res) {
10
if (paren.length() == 2 * n) {
11
res.add(paren.toString());
12
return;
13
}
14
15
if (left < n) {
16
paren.append('(');
17
getParenthesis(left + 1, right, n, paren, res);
18
paren.setLength(paren.length() - 1);
19
}
20
21
if (right < left) {
22
paren.append(')');
23
getParenthesis(left, right + 1, n, paren, res);
24
paren.setLength(paren.length() - 1);
25
}
26
}
27
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(2^n), 空间复杂度O(2^n)