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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new LinkedList<String>();
StringBuilder sb = new StringBuilder();
helper(list, sb, 0, 0, n);
return list;
}
private void helper(List<String> list, StringBuilder s, int left, int right, int n) {
if (s.length() == n * 2) {
list.add(s.toString());
return;
}
if (left < n) {
helper(list, new StringBuilder(s).append("("), left + 1, right, n);
}
if (right < left) {
helper(list, new StringBuilder(s).append(")"), left, right + 1, n);
}
}
}