22. Generate Parentheses

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:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

解法1:

比较经典的DFS题目,dfs的思想要掌握
C++

1

Java

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
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
helper("", res, n, n);
return res;
}
private void helper(String current, List<String> res, int left, int right) {
if (left == 0 && right == 0) {
res.add(current);
return;
}
if (left > 0) {
helper(current + "(", res, left - 1, right);
}
if (right > 0 && left < right) {
helper(current + ")", res, left, right - 1);
}
}
}