码迷,mamicode.com
首页 > 编程语言 > 详细

Generate Parentheses 【python】

时间:2014-08-27 16:27:27      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:style   blog   使用   io   strong   for   ar   div   log   

午睡醒敲到3点钟,搞了一个多小时。

应该是一种 非递归 的实现方法吧。

例如,4个括号的情况,可以看成是:

(3个括号的情况 连接上 1个括号的情况)+(2个括号的情况 连接上 2个括号的情况)+(1个括号的情况 连接上 3个括号的情况) + (‘(’ 连接上 3个括号的情况 连接上 ‘)’);

只是这样会每次产生重复的项,要先去掉,才能给下一次调用使用。

class Solution:
    # @param an integer
    # @return a list of string
    def generateParenthesis(self, n): 
        dp=[]
        for i in range(n):
            temp=[]
            if i==0:
                dp.append([‘()‘])
            else:
                for k in range(i):
                    for m in dp[k]:
                        for n in dp[i-k-1]:
                            temp.append(m+n)
                for o in dp[i-1]:
                    temp.append(‘(‘+o+‘)‘)
                dp.append(self.delRepetition(temp))
        return dp[i]
    def delRepetition(self,A):
        # A : list
        k=len(A)-1
        while k>0:
            for l in range(k):
                if A[k] == A[l]:
                    del A[k]   
                    break
            k-=1
        return A

if __name__==‘__main__‘:
    s=Solution()
    print(s.delRepetition([1,1,1,2,2,2,3,3,5]))
    print(s.generateParenthesis(4))

一直通不过,最后发现是因为剔除重复项的函数写错了,晕死。

 欢迎指出不足之处与讨论。

Generate Parentheses 【python】

标签:style   blog   使用   io   strong   for   ar   div   log   

原文地址:http://www.cnblogs.com/iois/p/3939612.html

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