DAY10:leetcode #22 Valid Parentheses

来源:互联网 发布:淘宝订单没有代付选项 编辑:程序博客网 时间:2024/05/29 19:00

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


0 0
原创粉丝点击