I am trying to pass a parameter "by value". I have tried making a deep copy of the parameter that is passed recursively in order to prevent any changes from circling back to the parent function calls.
Here is a snippet of code that tries to generate the array of all possible parentheses.
def generateParenthesis(n): #Iterate for each move. M = 2 * n retArray = [] def recHelper(numMoves, perm, stack): print("Function call: ", numMoves, perm, stack) newPerm = copy.deepcopy(perm) newStack = stack.copy() #Base case, no moves if (numMoves == 0): retArray.append(newPerm) return #Case when left move is valid if (numMoves != len(newStack)): #Apply the left move. Pass it recursively newPerm +='(' #Update the stack accordingly newStack.append('(') #Decrease numMoves newNumMoves = numMoves - 1 #Call it recursively recHelper(newNumMoves, newPerm, newStack) #Case when right move is valid if len(newStack) != 0: #Apply the right move. Pass it recursively newPerm +=')' #Update the stack accordingly, delete the top, last elm newStack.pop() #Decrease numMoves newNumMoves = numMoves - 1 #Call it recursively recHelper(newNumMoves, newPerm, newStack) #done return recHelper(M, "", []) return retArray Unfortunately, calling generateParenthesis(1) returns ['()','()(', '()()'] and not ['()'].
没有评论:
发表评论