Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22. 括号生成 #29

Open
Geekhyt opened this issue Feb 6, 2021 · 0 comments
Open

22. 括号生成 #29

Geekhyt opened this issue Feb 6, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 6, 2021

原题链接

回溯法

题目要求我们生成所有可能的有效的括号组合,数字 n 代表生成括号的对数。

使用回溯法进行解题,从空字符串开始构造,做加法。

  1. 当 l < r 时(构造用的左括号 < 构造用的右括号),不满足条件,直接剪枝。
  2. 当 l < n 时,可以一直插入左括号,最多插入 n 个。
  3. 当 r < l (构造用的右括号 < 构造用的左括号)时,可以插入右括号。
const generateParenthesis = function (n) {
    const res = []
    function generate(l, r, str) {
        // 递归终止条件
        if (l === n && r === n) {
            return res.push(str)
        }
        if (l < r) {
            return
        }
        if (l < n) {
            generate(l + 1, r, str + '(')
        }
        if (r < l) {
            generate(l, r + 1, str + ')')
        }
    }
    generate(0, 0, '')
    return res
}
  • 时间复杂度:O(2^n)
  • 空间复杂度:O(2^n)
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant