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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<String> (int n) {
List<String> result = new ArrayList<>();

generateParenthesisHelper(result, n, 0, 0, "");

return result;
}

private void generateParenthesisHelper(List<String> result, int n, int open, int close, String str) {
if (str.length() == 2 * n) {
result.add(str);
return;
}

if (close < open)
generateParenthesisHelper(result, n, open, close + 1, str + ")");

if (open < n)
generateParenthesisHelper(result, n, open + 1, close, str + "(");
}