Readable Java solution (track how many parentheses to close)


  • 0
    N
    public void generateParenthesisInternal(int n, StringBuilder bldr, List<String> solutions, int toClose) {
        if (n == 0) {
            for (int i = 1; i <= toClose; i++)
                bldr.append(')');
            solutions.add(bldr.toString());
            bldr.setLength(bldr.length() - toClose);
        }
        else {
            for (int i = 0; i <= toClose; i++) {
                for (int j = 1; j <= i; j++)
                    bldr.append(')');
                bldr.append('(');
                generateParenthesisInternal(n - 1, bldr, solutions, toClose + 1 - i);
                bldr.setLength(bldr.length() - 1 - i);
            }
        }
    }
    
    public List<String> generateParenthesis(int n) {
        List<String> solutions = new ArrayList<>();
        StringBuilder bldr = new StringBuilder();
        generateParenthesisInternal(n, bldr, solutions, 0);
        assert bldr.length() == 0;
        return solutions;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.