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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Store the remaining number of '(' and ')', and the remaining number of '(' should be less than ')' to form a valid parenthesis. Use recursion to do this. Time complexity is O(number of results). The number of results can be calculated using Catalan number.
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if (n <= 0) {
return res;
}
StringBuilder sb = new StringBuilder();
helperParenthesis(n, n, res, sb);
return res;
}
private void helperParenthesis(int l, int r, ArrayList<String> res, StringBuilder sb) {
if (l > r) {
return;
}
if (l == 0 && r == 0) {
res.add(sb.toString());
}
if (l > 0) {
helperParenthesis(l - 1, r, res, sb.append('('));
sb.deleteCharAt(sb.length() -1);
}
if (r > 0) {
helperParenthesis(l, r - 1, res, sb.append(')'));
sb.deleteCharAt(sb.length() -1);
}
}
}