108. Bracket generation
Title link
Source:
Link (LeetCode) : https://leetcode-cn.com/problems/generate-parentheses
Title description
The number n represents the logarithm of generating parentheses. Please design a function for generating all possible and effective combinations of parentheses.
Examples:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
More difficult
Find out the regularity of parenthesis generation
Topic analysis
- The brackets are divided into left brackets (left) and right brackets (right);
- According to n, generating n pairs of parentheses can be seen: left <= n, right <= left;
- Write a function that generates brackets: record the number of left brackets and right brackets, and store the generated brackets in res;
- Boundary: The number of left brackets does not exceed n, and the number of right brackets does not exceed the number of left brackets, ie left <n, right <left
- 当left == n && right == n时,return res;
/** * @param {number} n * @return {string[]} */ let generateParenthesis = (n) =>{ let res = []; function dfs(s, left, right){ if(left == n && right == n) return res.push(s); if(left < n) dfs(s+'(', left+1, right); if(right < left) dfs(s+')', left, right+1); } dfs('', 0, 0); return res; }