当前位置:网站首页>22. Generate parentheses

22. Generate parentheses

2022-06-11 05:17:00 qq_ twenty-six million three hundred and ninety-one thousand tw

 Insert picture description here

/* *  Numbers  n  Represents the logarithm of the generated bracket , Please design a function , Used to be able to generate all possible and   Effective   Bracket combination . *  Valid parenthesis : *  Input :n = 3 *  Output :["((()))","(()())","(())()","()(())","()()()"] *  Input :n = 1 *  Output :["()"] * * *  From the process of simulation : *  First, the string is empty , You can add (、 You can also add ) *  When the iteration addition ends , namely str The length of is 2n, Or invalid ; *  When is it invalid ?  That is, the number of left parentheses is less than that of right parentheses , In other cases, you can continue to iterate  *  When continuing the iteration , Sometimes you can add (, When can I add ) * ( The number of and n relevant ,) The number of is related to the number of left parentheses , Should be satisfied with :r<=l<=n,=>l<n,r<l Is the foundation of iteration  * *  difficulty : Abstract the relationship between the left and right brackets , And the basis of iteration  * */
var generateParenthesis = function(n) {
    
    var result = [],l=0,r=0,str='';
    back_tracking(n,result,l,r,str);
    return result;
};
var back_tracking=function(n,result,l,r,str){
    
    if(l<r){
    
        return;
    }
    if(str.length===2*n){
    
        result.push(str);
        return;
    }
    if(l<n){
    
        back_tracking(n,result,l+1,r,str+'(');
    }
    if(l>=r){
    
        back_tracking(n,result,l,r+1,str+')');
    }

}
console.log(generateParenthesis(1))
原网站

版权声明
本文为[qq_ twenty-six million three hundred and ninety-one thousand tw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110508404962.html