Leetcode 22. 括号生成

/**
 * @param {number} n
 * @return {string[]}
 */
var isValid = function(srcStr){
    let help = [];
    for(let i = 0;i<srcStr.length;i++){
        if(srcStr[i]=='('){
            help.push('(');
        }else{
            if(help.length){
                help.pop();
            }else{
                return false;
            }
        }
    }
    if(help.length){
        return false;
    }else{
        return true;
    }
}
var getAll = function(curStr,res,n){
    if(curStr.length >= n*2){
        // console.log(curStr);
        if(isValid(curStr)){
            res.push(curStr);
        }
    }else{
        let addLeftStr = curStr+'(';
        getAll(addLeftStr,res,n);
        let addRigthStr = curStr+')'
        getAll(addRigthStr,res,n);
    }
}
var generateParenthesis = function(n) {
   let res = [];
   getAll('',res,n);
   return res;
};

  

posted @ 2021-09-21 22:58  KYSpring  阅读(6)  评论(0编辑  收藏  举报