반응형
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
'Coding Interview' 카테고리의 다른 글
[LeetCode] DP - 118. Pascal's Triangle (0) | 2022.10.04 |
---|---|
[LeetCode] DFS, DP 322. Coin Change (1) | 2022.10.04 |
[LeetCode] DP, String - 5. Longest Palindromic Substring (0) | 2022.10.03 |
[LeetCode] DP - 53. Maximum Subarray (0) | 2022.10.01 |
알고리즘 유형을 알아보자 (0) | 2022.10.01 |