返回介绍

lcci / 08.09.Bracket / README_EN

发布于 2024-06-17 01:04:43 字数 4960 浏览 0 评论 0 收藏 0

08.09. Bracket

中文文档

Description

Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n pairs of parentheses.

Note: The result set should not contain duplicated subsets.

For example, given n = 3, the result should be:


[

  "((()))",

  "(()())",

  "(())()",

  "()(())",

  "()()()"

]

Solutions

Solution 1: DFS + Pruning

The range of $n$ in the problem is $[1, 8]$, so we can directly solve this problem quickly through "brute force search + pruning".

We design a function dfs(l, r, t), where $l$ and $r$ represent the number of left and right parentheses respectively, and $t$ represents the current parentheses sequence. Then we can get the following recursive structure:

  • If $l > n$ or $r > n$ or $l < r$, then the current parentheses combination $t$ is illegal, return directly;
  • If $l = n$ and $r = n$, then the current parentheses combination $t$ is legal, add it to the answer array ans, and return directly;
  • We can choose to add a left parenthesis, and recursively execute dfs(l + 1, r, t + "(");
  • We can also choose to add a right parenthesis, and recursively execute dfs(l, r + 1, t + ")").

The time complexity is $O(2^{n\times 2} \times n)$, and the space complexity is $O(n)$.

class Solution:
  def generateParenthesis(self, n: int) -> List[str]:
    def dfs(l, r, t):
      if l > n or r > n or l < r:
        return
      if l == n and r == n:
        ans.append(t)
        return
      dfs(l + 1, r, t + '(')
      dfs(l, r + 1, t + ')')

    ans = []
    dfs(0, 0, '')
    return ans
class Solution {
  private List<String> ans = new ArrayList<>();
  private int n;

  public List<String> generateParenthesis(int n) {
    this.n = n;
    dfs(0, 0, "");
    return ans;
  }

  private void dfs(int l, int r, String t) {
    if (l > n || r > n || l < r) {
      return;
    }
    if (l == n && r == n) {
      ans.add(t);
      return;
    }
    dfs(l + 1, r, t + "(");
    dfs(l, r + 1, t + ")");
  }
}
class Solution {
public:
  vector<string> generateParenthesis(int n) {
    vector<string> ans;
    function<void(int, int, string)> dfs;
    dfs = [&](int l, int r, string t) {
      if (l > n || r > n || l < r) return;
      if (l == n && r == n) {
        ans.push_back(t);
        return;
      }
      dfs(l + 1, r, t + "(");
      dfs(l, r + 1, t + ")");
    };
    dfs(0, 0, "");
    return ans;
  }
};
func generateParenthesis(n int) []string {
  ans := []string{}
  var dfs func(int, int, string)
  dfs = func(l, r int, t string) {
    if l > n || r > n || l < r {
      return
    }
    if l == n && r == n {
      ans = append(ans, t)
      return
    }
    dfs(l+1, r, t+"(")
    dfs(l, r+1, t+")")
  }
  dfs(0, 0, "")
  return ans
}
function generateParenthesis(n: number): string[] {
  function dfs(l, r, t) {
    if (l > n || r > n || l < r) {
      return;
    }
    if (l == n && r == n) {
      ans.push(t);
      return;
    }
    dfs(l + 1, r, t + '(');
    dfs(l, r + 1, t + ')');
  }
  let ans = [];
  dfs(0, 0, '');
  return ans;
}
impl Solution {
  fn dfs(left: i32, right: i32, s: &mut String, res: &mut Vec<String>) {
    if left == 0 && right == 0 {
      res.push(s.clone());
      return;
    }
    if left > 0 {
      s.push('(');
      Self::dfs(left - 1, right, s, res);
      s.pop();
    }
    if right > left {
      s.push(')');
      Self::dfs(left, right - 1, s, res);
      s.pop();
    }
  }

  pub fn generate_parenthesis(n: i32) -> Vec<String> {
    let mut res = Vec::new();
    Self::dfs(n, n, &mut String::new(), &mut res);
    res
  }
}
/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function (n) {
  function dfs(l, r, t) {
    if (l > n || r > n || l < r) {
      return;
    }
    if (l == n && r == n) {
      ans.push(t);
      return;
    }
    dfs(l + 1, r, t + '(');
    dfs(l, r + 1, t + ')');
  }
  let ans = [];
  dfs(0, 0, '');
  return ans;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文