[Leetcode] 22. Generate Parentheses โ
#์กฐํฉ
Problem โ
์ซ์ n
์ด ์ฃผ์ด์ง๋, ๊ดํธ (
,)
๋ฅผ n
๊ฐ์ ์์ด๋ง๋ ์ฌ๋ฐ๋ฅธ ๊ดํธ๊ฐ ๋ ์ ์๋ ๊ฒฝ์ฐ๋ฅผ ๋ชจ๋ ๋ง๋ค์ด๋ผ.
Solution โ
- ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ ๋ฐฉ๋ฒ
- ์ฃผ์ด์ง N๋ณด๋ค ์ด๋ฆฐ๊ดํธ๊ฐ ์ ์ผ๋ฉด ์ด๋ฆฐ๊ดํธ๋ฅผ ์ถ๊ฐํ๋ ํจ์ ํธ์ถ๊ณผ ์ด๋ฆฐ๊ดํธ๋ณด๋ค ๋ซํ๊ดํธ์ ์๊ฐ ์ ์ผ๋ฉด ๋ซํ๊ดํธ๋ฅผ ์ถ๊ฐํ๋ ๋ก์ง์ ์ํ
- ์ฌ๊ทํจ์๊ฐ ๊น์ด์ง๋ N๋ณด๋ค ์ด๋ฆฐ๊ดํธ์ ๋ซํ๊ดํธ์ ์๊ฐ ์ปค์ง์ง ์๋๋ก ์กฐ๊ฑด ์ฒ๋ฆฌ
- ์ด๋ฆฐ๊ดํธ์ ๋ซํ๊ดํธ์ N์ ๊ฐ์ด ๊ฐ์๋ ํ์ฌ ์ํ์ ๋ฌธ์์ด์ ์ ์ฅํ๋ค.
JS CODE โ
javascript
/**
* @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
}