leetcode

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

The idea is if open parentheses is less the the target number, keep inserting "(", if open is greater than closed parenthese, start inserting ")".

public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList<String>();
        generateParenthesis(results, new StringBuilder(), 0, 0, n);
        return results;
    }

    private void generateParenthesis(List<String> results, StringBuilder sb, int open, int close, int n) {
        if(close == n) {
            results.add(sb.toString());
            return;
        } else {
            if (open<n) {
                sb.append("(");
                generateParenthesis(results, sb, open+1, close, n);
                sb.deleteCharAt(sb.length()-1);
            }
            if (open>close) {
                sb.append(")");
                generateParenthesis(results, sb, open, close+1, n);
                sb.deleteCharAt(sb.length()-1);
            }            
        }
    }