DAY10:leetcode #22 Valid Parentheses

本文介绍了一种生成合法括号组合的算法,通过遍历所有可能的括号序列并验证其合法性来实现。此外,还提供了一种更高效的解决方案,利用递归方法结合左括号与右括号的数量控制,避免无效括号序列的生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

Subscribe to see which companies asked this question


第一版的代码,思路很清晰,求括号的全排序,去重,检验是否有效。

但这样的时间花费太大了,超时。

class Solution(object):
    def isValid(self, s):  
        """ 
        :type s: str 
        :rtype: bool 
        """  
        s_list = list(s)  
        sstack = []  
        for item in s_list:  
            if item in ['{','(','[']:  
                sstack.append(item)  
            else:  
                try:  
                    if item == ')':  
                        temp = sstack.pop()  
                        if temp != '(':  
                            return False  
                except Exception,e:  
                    return False  
        if len(sstack) == 0:  
            return True  
        else:  
            return False  
    def permutation(self, result, str, list):  
        """ 
            取一个数组的全排列 
            list:为输入列表 
            str:传空字符串 
            result: 为结果列表 
        """  
        if len(list) == 1:  
            result.append(str + "," + list[0])  
        else:  
            for temp_str in list:  
                temp_list = list[:]  
                temp_list.remove(temp_str)  
                self.permutation(result, str + "," + temp_str, temp_list)  
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = []
        input = []
        data = []
        result_s = set()
        for i in range(n):
            input.append('(')
            input.append(')')
        self.permutation(result,"",input)  
        for r in result:
            result_s.add(r.replace(',',''))
        result = list(result_s)
        for r in result:
            if self.isValid(r):
                data.append(r)
        return data
        

在网上找了一个更好的解法,还没有时间想得太明白:

看到这道题目首先想到的是catlan Number  根据catlan number我们可以知道最后的解的数量是catlan number

这里要求我们求解我们可以用bfs枚举来解决。

1.当左括号数量小于n 时候添加左括号

2.当有括号数量小于左括号时候添加右括号

3.当总括号长度等于2n时候将解加入解的集合。

this is a catlan number problem. we can know the final solution length is the corresponding catlan number. 

to give specific solutions 

1. when # of left parentheses is no greater than n we append left parentheses

2. when # of right parentheses is not greater than left parentheses we append right parentheses

3. when the total length is 2n we append it to solution

code is as follow:

class Solution:
    # @param an integer
    # @return a list of string
    def findp(self,valuelist,solution,n,left,right):
        if len(valuelist)==2*n:
            solution.append(valuelist)
        if left<n:
            self.findp(valuelist+'(',solution,n,left+1,right)
        if right<left:
            self.findp(valuelist+')',solution,n,left,right+1)
    def generateParenthesis(self, n):
        solution=[]
        self.findp('',solution,n,0,0)
        return solution


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值