Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<String>();
        if(n < 1){
            return ans;
        }
        helper(0, new StringBuilder(), ans, n);
        return ans;
    }
    private void helper(int count, StringBuilder path, List<String> ans, int n){
        if(path.length() == 2 * n){
            if(count == 0){
                ans.add(path.toString());
            }
            return;
        }
        if(count < n){
            path.append('(');
            helper(count + 1, path, ans, n);
            path.deleteCharAt(path.length() - 1);
        }
        if(count > 0){
            path.append(')');
            helper(count - 1, path, ans, n);
            path.deleteCharAt(path.length() - 1);
        }
    }

results matching ""

    No results matching ""