0%

Leetcode022-generateParenthneses

Description

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:

Example

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

Solution

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
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if (n == 0) return res;

helper(n, res, 0, 0, "");
return res;
}

private void helper(int n, List<String> res, int left, int right, String cur){
if (left == n && right == n) {
res.add(cur);
return;
}
int maxLeft = n - left;
if (maxLeft > 0){
cur += "(";
helper(n, res, left + 1, right, cur);
if (cur.length() > 1) cur = cur.substring(0, cur.length() - 1);
else cur = "";
}

int maxRight = left - right;
if (maxRight > 0){
cur += ")";
helper(n, res, left, right + 1, cur);
if (cur.length() > 1) cur = cur.substring(0, cur.length() - 1);
else cur = "";
}
}
}