My fast python solution using set()


  • 0
    M
    my python solution using set
    When I first looked at the problem, I thought that we use recursive, so I wrote the code below. From n to 1, keep calling n-1, and when I get generateParenthesis(1), I add ")" at the end of every list in the result. Then add "(" before every ")" in the list. But that will have some duplicate cases, so use set() to remove the duplicate lists.
    
    
    
    
    class Solution(object):
            def generateParenthesis(self, n):
                """
                :type n: int
                :rtype: List[str]
                """
                if n == 0:
                    return []
                elif n == 1:
                    return ["()"]
                else:
                    L = self.generateParenthesis(n-1)
                    L1=[]
                    for i in L:
                        i=i+")"
                        for j in range(len(i)):
                            if i[j]==")":
                                L1.append(i[:j]+"("+i[j:])
                L2 = list(set(L1))
                return L2

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.