美文网首页
LeetCode22.括号生成 JavaScript

LeetCode22.括号生成 JavaScript

作者: LHH大翰仔仔 | 来源:发表于2019-02-18 09:21 被阅读2次

    给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

    例如,给出n = 3,生成结果为:

    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]
    

    答案参考:

    /**
     * @param {number} n
     * @return {string[]}
     */
    var generateParenthesis = function(n) {
        if (n == 1) {
            return ["()"];
        }
        
        let maxCombo = [];
        maxCombo[0] = 0;
        for (let i = 1; i < n * 2; i++) {
            if (i > n + 1) {
                maxCombo[i] = 0;
            } else {
                maxCombo[i] = 1;
            }
        }
        
        let maxComboCount = parseInt(maxCombo.join(''), 2);
        let leastComboCount = parseInt(Array(n).fill(1).join(''), 2);
        let results = [];
    
        for (let i = leastComboCount; i < maxComboCount; i++) {
            let binary = i.toString(2);
    
            let balancer_0 = n * 2 - binary.length;
            let balancer_1 = 0;
            let cont = false;
    
            let result = '';
            
            for (let j = 0; j < balancer_0; j++) {
                result += '(';
            }
            
            for (let j = 0; j < binary.length; j++) {
                if (binary[j] == '0') {
                    balancer_0 += 1;
                    result += '(';
                } else {
                    balancer_1 += 1;
                    result += ')';
                }
    
                if (balancer_1 > balancer_0) {
                    cont = true;
                    break;
                }
            }
    
            if (cont || balancer_0 != balancer_1) {
                continue;
            }
            
            results.push(result);
        }
        return results;
    };
    
    欢迎关注

    相关文章

      网友评论

          本文标题:LeetCode22.括号生成 JavaScript

          本文链接:https://www.haomeiwen.com/subject/devoeqtx.html