Generate Valid Parentheses214 views

AlgoPill
 function generateValidParentheses(n){
    function generate(l,r,n,p){
        var output=[];
        if(r>=n){
            output.push(p.join(''));
            return output;
        }
        if(r<l){
            p[l+r]=')';
            output = output.concat(generate(l,r+1,n,p));
        }
        if(l<n){
            p[l+r]='(';
            output = output.concat(generate(l+1,r,n,p));
        }
        return output;
    }

    return generate(0,0,n,[]);
}

Problem Statement: Given n pairs of parentheses, generate set of all valid parentheses permutations

Solution: Given n pairs of parentheses this solution uses a simple logic that  left parentheses can be place in the string as long number of left parentheses used so far is less than n, and a right parentheses can be place in the string as long as number of right parentheses used so far is less than the number of left parentheses used so far.

Post a Comment

You must be logged in to post a comment.