zoukankan      html  css  js  c++  java
  • 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
    

    题目来源

  • 相关阅读:
    Redhat as 版本下启用 Telnet 和 FTP 服务
    Eclipse中设置编码的方式
    rhel3上安装Oracle(来自Oracle网站)
    home/end的快捷键~
    Red Hat Linux 9中文本模式与图形模式的切换
    Highcharts:非常漂亮的图表API
    Linux裸设备总结(ZT)
    Red Hat Linux操作系统下从文本模式切换到图形模式的方法
    pear
    Java中的asList
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8328230.html
Copyright © 2011-2022 走看看