码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#22 Generate Parentheses

时间:2015-08-01 21:48:07      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

LeetCode#22 Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/acetseng/p/4694600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!