My easy backtracking Java solution


  • 0
    L

    Let me know if you find a way to improve this code. Thanks!

    public int p;
    public List<String> answers;
    
    public List<String> generateParenthesis(int p) {
        answers = new ArrayList<String>();
        this.p = p;
        helper( 1, 0, "(", "" ); //first has to be "("
        return answers;
    }
    
    public void helper( int leftP, int rightP, String s, String curr ){
        curr += s ;
        
        if( leftP == p && rightP == p ){
            answers.add( curr );
            return;
        }
        
        // The idea is the leftP always more than or equal to rightP.
        if( leftP < rightP || leftP > p || rightP > p ) return;
        
        helper( leftP +1, rightP, "(", curr );
        helper( leftP, rightP +1, ")", curr );
        
    }

Log in to reply
 

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