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:
Tips:
recursion, keep left parenthesis greater than or equal to right parenthesis.
Java Code:
public class Solution {
// Catalan Number
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
String str = "";
generateParenthesis(n, n, str, result);
return result;
}
public void generateParenthesis(int lc, int rc, String str, List<String> result) {
if (lc == 0 && rc == 0) {
if (str != "") {
result.add(str);
}
return;
}
if (lc > 0) {
generateParenthesis(lc - 1, rc, str + '(', result);
}
if (rc > 0 && rc > lc) {
generateParenthesis(lc, rc - 1, str + ')', result);
}
}
}