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<String>();
if(n < 0)
return res;
helper(res, "", 0, 0, n);
return res;
}
public void helper(List<String> res, String curr, int left, int right, int n) {
if(curr.length() == 2 * n) {
if(left == right) {
res.add(curr);
}
return;
}
if(right > left)
return;
helper(res, curr + "(", left + 1, right, n);
helper(res, curr + ")", left, right + 1, n);
}
}