Short and easy understandable Java solution


  • 1
    A

    Since all the parentheses are identical( all"()"pair), so we don't need stack to keep track of order.
    You have n parentheses, so 2*n position in total; in each position you have two choice, "(" or ")".
    As a result, at each position try either "(" or ")" and only pick those situations when close ==n and open ==n.

    Ofc you can make it faster, but I just want it to be short and readable.

    public static List<String> generateParenthesis(int n) {
        List<String> result = new LinkedList<String>();
        generate(n,0,0,result,"");
        
        return result;
    }
    
    static void generate(int n,int open,int close,List<String> result,String current){
        if(close>open) return;
        if(close==n && open ==n) {
            result.add(current);
        }
        else {
            if(open<n) generate(n,open+1,close,result,current+"(");
            generate(n,open,close+1,result,current+")");
        }
    }

Log in to reply
 

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