• LeetCode#22 Generate Parentheses


    Problem Definition:

    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:

    "((()))", "(()())", "(())()", "()(())", "()()()"

    Solution: 这个问题,用回溯或者遍历法都比较好解,其实思路都是一样的,从空字符开始,逐步插入成对的括号'()'。关键是怎么选择插入的位置。

    比如当前状态是 ( ), 则一共有三个位置可以插入:

                             1 ( 2 )        其中,位置1和位置3是对称的,可以只考虑一边。于是下一次插入新的括号对,可能形成的串是: ( )( ),( ( ) )。

    1)遍历法的实现:

     1     # @param {integer} n
     2     # @return {string[]}
     3     def generateParenthesis(self, n):
     4         if n<1:
     5             return []
     6         res=['']
     7         tmp=[]
     8         c=0
     9         while c<2*n:
    10             for localStr in res:
    11                 for index in range(len(localStr)/2+1):
    12                     tmpStr=localStr[:index]+'()'+localStr[index:]
    13                     tmp.append(tmpStr[:])
    14             res=tmp
    15             c+=2
    16         return res

    以上想法也可以写成回溯(解空间的深度优先遍历)的形式。

     1     # @param {integer} n
     2     # @return {string[]}
     3     def generateParenthesis(self, n):
     4         res=set()
     5         if n==0:
     6             return []
     7         backTrack('()', 2, n, res)
     8         return res
     9 
    10     def backTrack(self, localStr, index, n, res): #index from 1
    11         if len(localStr)==2*n:
    12             sub=localStr[:]
    13             if sub not in res:
    14                 res.append(sub)
    15         else:
    16             for i in range(index):
    17                 tmpStr=localStr[:i]+'()'+localStr[i:]
    18                 self.backTrack(tmpStr, index+1, n, res)
  • 相关阅读:
    白兔的字符串(字符串hash+模拟map)
    [TJOI2013]单词(AC自动机+前缀和维护)
    [SDOI2014]数数(ac自动机+数位DP)
    阿狸的打字机(AC自动机+dfs序 + 维护区间值)
    string(AC自动机 在线询问转离线询问)
    E
    JMX超详细解读
    快速生成100万数据人员信息数据
    聊聊spring之bean对象的实例化过程
    聊聊spring之贯穿全局的重要对象BeanDefinition
  • 原文地址:https://www.cnblogs.com/acetseng/p/4694600.html
Copyright © 2020-2023  润新知