leetcode 22. generate parentheses

22. Generate Parentheses

Difficulty: Medium

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
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Solution

Language: 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
26
27
class  {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if (n <= 0) {
return result;
}
dfsHelper(n, result, new char[n * 2], 0, 0);
return result;
}

private void dfsHelper(int n, List<String> result, char[] chars, int index, int p) {
if (p < 0 || p > n) {
return;
}
if (index == chars.length) {
if (p == 0) {
result.add(new String(chars));
}
return;
}
chars[index] = '(';
dfsHelper(n, result, chars, index + 1, p + 1);
chars[index] = ')';
dfsHelper(n, result, chars, index + 1, p - 1);

}
}