题目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

    [
      "((()))",
      "(()())",
      "(())()",
      "()(())",
      "()()()"
    ]

翻译

生成所有的括号匹配

Hints

Related Topics: String, Backtracking

利用回溯法

代码

Java

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new List<String>();
        backtrack("", list, n, n);
        return list;
    }
    public void backtrack(String s, List<String> list, int left, int right){
        if(left > right){
            return;
        }
        if(left > 0){
            backtrack(s+"(", list, left-1, right);
        }
        if(right > 0){
            backtrack(s+")", list, left, right-1);
        }
        if(left==0 && right==0){
            list.add(s);
            return;
        }
    }
}

Python

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        def backtrack(l, s, left, right, maxlen):
            if len(s)==maxlen*2:
                l.append(s)
                return
            if left < maxlen:
                backtrack(l, s+'(', left+1, right, maxlen)
            if right < left:
                backtrack(l, s+')', left, right+1, maxlen)
            
        result = []
        backtrack(result, '', 0, 0, n)
        return result

相关文章:

  • 2021-07-30
  • 2021-10-07
  • 2021-08-13
  • 2022-01-04
  • 2021-12-04
  • 2022-02-03
  • 2021-10-23
  • 2022-01-21
猜你喜欢
  • 2022-01-26
  • 2021-10-30
  • 2021-06-26
  • 2021-07-06
  • 2021-07-07
  • 2021-09-21
  • 2021-10-19
相关资源
相似解决方案