prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Coding

Generate parenthesis

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n= 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        parenthesisList = []
        self.generateParenthesisHelper("", parenthesisList, 0, 0, n)
        return parenthesisList

    def generateParenthesisHelper(self, subList, parenthesisList, open, close, max):
        if len(subList) == 2 * max:
            parenthesisList += [subList]
            #print '        *** subList: ', subList, ' ***'
            return

        if open < max:
            #print 'open = ', open, 'max = ', max
            self.generateParenthesisHelper(subList + "(", parenthesisList, open + 1, close, max)
            #print '  > return from ( < '

        if close < open:
            #print 'close = ', close, 'open = ', open
            self.generateParenthesisHelper(subList + ")", parenthesisList, open, close + 1, max)
            #print '  > return from ) < '
PreviousClone GraphNextFibonacci Number

Last updated 5 years ago

Was this helpful?