Parens: Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n pairs of parentheses.
public class Solution {
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
public List<String> generateParenthesis(int n) {
// write your code here
List<String> result = new ArrayList<String>();
if(n == 0) return result;
StringBuilder sb = new StringBuilder();
helper(n, n, result, sb);
return result;
}
public void helper(int l, int r, List<String> result, StringBuilder sb) {
if(l == 0 && r == 0) {
result.add(sb.toString());
return;
}
if(l > 0) {
sb.append('(');
helper(l - 1, r, result, sb);
sb.deleteCharAt(sb.length() - 1);
}
if(l >= 0 && l < r) {
sb.append(')');
helper(l, r - 1, result, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
}