Brush 69-bracket generation

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

  1. The brackets are divided into left brackets (left) and right brackets (right);
  2. According to n, generating n pairs of parentheses can be seen: left <= n, right <= left;
  3. Write a function that generates brackets: record the number of left brackets and right brackets, and store the generated brackets in res;
  4. 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
  5. 当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;
}

  

Guess you like

Origin www.cnblogs.com/liu-xin1995/p/12677417.html