22. Generate Parentheses

22. Generate Parentheses

题目

 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:

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

解析

  • 这道题要生成正确形式的括号匹配的数量,其实就是卡特兰数,至于要输出所有括号的正确组合形式,可以采用递归。用两个变量l和r记录剩余左括号和右括号的数量,当且仅当左右括号数量都为0时,正常结束。当然还有一点限制,就是剩余的右括号数量比左括号多时才能添加右括号
class Solution_22 {
public:
    void dfs(string str,int left,int right,int total,vector<string>& vec)
    {
        if (left+right==total)
        {
            vec.push_back(str);
        }
        if (left<total/2)  // 不能用left<=total/2等号
        {
            dfs(str + '(', left + 1, right, total, vec);
        }
        if (left>right&&right<total/2) //左括号多余右括号
        {
            dfs(str + ')', left, right + 1, total, vec);
        }
        
        return;
    }

    vector<string> generateParenthesis(int n) {
        vector<string> vec;
        string str;
        if (n==0)
        {
            return vec;
        }
        dfs("", 0, 0, 2 * n,vec);
        return vec;
    }
};

def generateParenthesisDFS(self, n):
        def generate(s, left, right, ans):
            if len(s) == 2*n:
                ans.append(s)
            if left < n:
                generate(s+'(', left+1, right, ans)
            if left > right:
                generate(s+')', left, right+1, ans)
        left, right, ans = 0, 0, []
        generate('', left, right, ans)
        return ans

    def generateParenthesisBFS(self, n):
        def valid(s, n):
            bal, left = 0, 0
            for c in s:
                if c == '(': 
                    bal += 1
                    left += 1
                else:
                    bal -= 1
                if bal < 0:
                    return False
            return bal >= 0 and left <= n

        ans = []
        q = Queue.Queue()
        q.put('(')
        while not q.empty():
            s = q.get()
            if len(s) == 2*n:
                ans.append(s)
                continue
            for i in ['(', ')']:
                if valid(s+i, n):
                    q.put(s+i)
        return ans

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8328230.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞