Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
StringBuilder paren = new StringBuilder();
getParenthesis(0, 0, n, paren, res);
return res;
}
public void getParenthesis(int left, int right, int n, StringBuilder paren, List<String> res) {
if (paren.length() == 2 * n) {
res.add(paren.toString());
return;
}
if (left < n) {
paren.append('(');
getParenthesis(left + 1, right, n, paren, res);
paren.setLength(paren.length() - 1);
}
if (right < left) {
paren.append(')');
getParenthesis(left, right + 1, n, paren, res);
paren.setLength(paren.length() - 1);
}
}
}
3. Time & Space Complexity