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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
Solution
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
if(n <= 0) return result;
generate(result, "", 0, 0, n);
return result;
}
public void generate(ArrayList<String> result, String temp, int lp, int rp, int n){
if(lp == n){
for(int i = rp; i < n; i ++)
temp += ')';
result.add(temp);
return;
}
generate(result, temp + '(', lp + 1, rp, n);
if (lp > rp)
generate(result, temp + ')', lp, rp + 1, n);
}
}