【发布时间】:2021-06-18 16:50:52
【问题描述】:
我正在尝试“按值”传递参数。我尝试制作递归传递的参数的深层副本,以防止任何更改循环回父函数调用。
这是一段尝试生成所有可能括号的数组的代码。
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
不幸的是,调用generateParenthesis(1) 返回['()','()(', '()()'] 而不是['()']。
【问题讨论】:
-
是将 int 传递给 generateParenthesis 的结果,并且列表中的“()”列表等于您传递的参数值吗?因为如果这是唯一需要的结果,这是一种非常奇怪的方法。我的假设与测试有关,以证明您对递归的理解。
-
perm参数是一个字符串,它是不可变的,因此必须进行复制(尽管除了浪费执行时间之外无害)。 -
我不认为你的递归函数做你认为它做的事情。你能告诉我们
generateParenthesis(2)和generateParenthesis(3)的结果应该是什么吗? -
@Reti43 generateParenthesis(2) 的结果应该是:['()()', '(())'],这是唯一有效的括号排列,包括两对左和对
-
@Justin 你有什么想法哦解决方案?
标签: python python-3.x recursion pass-by-value