题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串一维数组 */ function permute( all,leftUsed,rightUsed){ // 同样还是一个类似全排列,但是要注意的是,排列的对象是一个有规则的括号,每一次排列只有两种选择,左括号或者右括号 // 规则:进行下一步排列前,左方的 "("的数量 要大于 ")"的数量 // left,right是排列剩下的左右括号数量 if(all -rightUsed==0){return []} if(all-leftUsed==0&&all-rightUsed==1){return [")"]} // let lC = leftUsed; // let rC = rightUsed; let left = null let right= null let res = [] if(all-leftUsed>0){ left = permute(all,leftUsed+1,rightUsed) } if(rightUsed<leftUsed){ right = permute(all,leftUsed,rightUsed+1) } if (left){ for(let l of left){ res.push("("+l) // console.log(res) } } if (right){ for(let r of right){ res.push(")"+r) console.log(res) } } // console.log("left",left) // console.log("right",right) return(res) } function generateParenthesis( n ) { // write code here let res = permute(n,0,0) return res } module.exports = { generateParenthesis : generateParenthesis };