Coding Interview

[LeetCode] DP, DFS - 22. Generate Parentheses

milliwonkim 2022. 10. 4. 19:10
반응형
SMALL

문제

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

 

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

 

Constraints:

  • 1 <= n <= 8

코드

const generateParenthesis = (n) => {
    const result = [];
    const dfs = (s, l, r) => {
        if(n * 2 === s.length) {
            result.push(s)
            return;
        }

        if(l < n) dfs(s + '(', l + 1, r);
        if(r < l) dfs(s + ')', l, r + 1);
    }

    dfs('', 0, 0)

    return result;
}
반응형
LIST