숫자 n
이 주어질때, 괄호 (
,)
를 n
개의 쌍이맞는 올바른 괄호가 될 수 있는 경우를 모두 만들어라.
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function (n) {
let answer = []
const combination = (openCnt, closeCnt, str) => {
if (n < openCnt || n < closeCnt) return
if (n === openCnt && n === closeCnt) {
answer.push(str)
}
if (openCnt < n) combination(openCnt + 1, closeCnt, str + '(')
if (closeCnt < openCnt) combination(openCnt, closeCnt + 1, str + ')')
}
combination(0, 0, '')
return answer
}