Generate Parentheses
/**
* 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 ArrayList<String> generateParenthesis(int n) {
if(n == 0)
return new ArrayList<String>();
return generateParenthesis(n, 0, 0, new StringBuffer());
}
// overloading...
public ArrayList<String> generateParenthesis(int n, int l, int r, StringBuffer buf){
ArrayList<String> res = new ArrayList<String>();
if(l > n || r > n)
return res;
if(r == n){
res.add(buf.toString());
return res;
}
// adding open parenthesis
if(l < n){
StringBuffer newBuf = new StringBuffer(buf);
newBuf.append("(");
res.addAll(generateParenthesis(n, l + 1, r, newBuf));
}
// adding close parenthesis
if(r < l){
StringBuffer newBuf = new StringBuffer(buf);
newBuf.append(")");
res.addAll(generateParenthesis(n, l, r + 1, newBuf));
}
return res;
}
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
String item = new String();
if (n <= 0) {
return res;
}
generate(res, item, n, n);
return res;
}
public void generate(List<String> res, String item, int left, int right) {
if (left > right) {
return;
}
if (left == 0 && right == 0) {
res.add(new String(item));
}
if (left > 0) {
generate(res, item + "(", left - 1, right);
}
if (right > 0) {
generate(res, item + ")", left, right - 1);
}
}
}