Problem

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

Example

Given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

JavaScript Code

function generateParenthesis(n) {
    var result = [];
    var diff = [];
 
    result.push("");
    diff.push(0);
 
    for (var i = 0; i < 2 * n; i++) {
        var temp1 = [];
        var temp2 = [];
 
        for (var j = 0; j < result.length; j++) {
            var s = result[j];
            var k = diff[j];
 
            if(i < 2 * n - 1) {
                temp1.push(s + "(");
                temp2.push(k + 1);
            }
 
            if (k > 0 && i < 2 * n - 1 || k == 1 && i == 2 * n - 1) {
                temp1.push(s + ")");
                temp2.push(k - 1);
            }
        }
 
        result = JSON.parse(JSON.stringify(temp1));
        diff = JSON.parse(JSON.stringify(temp2));
    }
 
    return result;
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts