蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

题目

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 generateParenthesis(int n) {
        List list = new List();
        backtrack("", list, n, n);
        return list;
    }
    public void backtrack(String s, List 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

转载于:https://www.cnblogs.com/cookielbsc/p/7502164.html

你可能感兴趣的:(蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium])