Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成括号递归作为列表与字符串传递_Python_Python 3.x_Recursion - Fatal编程技术网

Python 生成括号递归作为列表与字符串传递

Python 生成括号递归作为列表与字符串传递,python,python-3.x,recursion,Python,Python 3.x,Recursion,我在解决leetcode中的生成括号问题。如果我使用以下代码(cur作为要附加的列表): 这里f是前括号的计数器,b是后括号的计数器 def generateParenthesis(n: int) -> List[str]: def recursion(f, b, cur=[]): if len(cur)==(n*2): a ="".join(cur) output.append(a) re

我在解决leetcode中的生成括号问题。如果我使用以下代码(cur作为要附加的列表):

这里f是前括号的计数器,b是后括号的计数器

def generateParenthesis(n: int) -> List[str]:

    def recursion(f, b, cur=[]):

        if len(cur)==(n*2):
            a ="".join(cur)
            output.append(a)
            return
        if f:
            cur.append("(")
            recursion(f-1,b, cur)
        if b:
            cur.append(")")
            recursion(f,b-1, cur)
    output = []
    f = n
    b = n
    recursion(f, b, cur)

    return output
当我运行上述解决方案时,我得到n=3的输出:

[“(())”]

如果我使用cur作为字符串,而不是附加到列表中,并将“(”添加到列表中,我得到了正确的答案

def generateParenthesis(n: int) -> List[str]:

    def recursion(f, b, cur=""):

        if b < f or b<0 or f<0:
            return

        if len(cur)==n*2:
            output.append(cur)
            return
        if f:
            recursion(f-1,b, cur+"(")
        if b:
            recursion(f,b-1, cur+")")


    output = []
    f = n
    b = n
    recursion(f, b)

    return output
def generateParenthesis(n:int)->List[str]:
定义递归(f,b,cur=”“):

如果b->List[str]:
递归(f,b,cur)
的语法,因为代码中没有定义List,区域中也没有定义cur

现在让我们看看第一部分中的代码

def generateParenthesis(n: int) -> List[str]:

    def recursion(f, b, cur=[]):

        if len(cur)==(n*2):
            a ="".join(cur)
            output.append(a)
            return
        if f:
            cur.append("(")
            recursion(f-1,b, cur)
        if b:
            cur.append(")")
            recursion(f,b-1, cur)
    output = []
    f = n
    b = n
    recursion(f, b, cur)

    return output
变量
cur
in通过引用传递到递归。这意味着,所有被调用的递归共享相同的
cur
变量。因此,在执行过程中,一旦生成
“(())”
,其他递归仍将增加
cur
的长度,使
“((())”
唯一的输出。因此,如果将条件更改为
如果len(cur)>=n*2
,您将获得以下输出

['((())'、'((()))'、'((()())'、'(((())))]]

为了使代码正常工作,一种简单的方法是每次调用递归时创建一个新列表。例如,
递归(f-1,b,deepcopy(cur))
,其中
deepcopy
是来自copy import deepcopy
。但我相信在这种情况下,您更愿意使用不可变字符串

另一方面,您也可以将列表视为堆栈。每次递归调用都会附加一个括号,这意味着在堆栈中推送一个括号。因此,您还应该在递归调用之后弹出推式括号。尽管在这种情况下,应使用以前的检查条件

由于Python的
列表
类似于C++的
向量
,因此我们可以只维护最后一个元素的索引,而不是实际弹出。修改后的代码应该是

def generateParenthesis(n):

    def recursion(f, b, cur=[None] * (2*n), idx= 0):

        if b < f or b<0 or f<0:
            return

        if idx >= (n*2):
            a ="".join(cur)
            output.append(a)
            return
        if f:
            cur[idx] = "("
            recursion(f-1,b, cur, idx + 1)
        if b:
            cur[idx] = ")"
            recursion(f,b-1, cur, idx + 1)

    output = []
    f = n
    b = n
    recursion(f, b)

    return output
def generateParenthesis(n):
def递归(f,b,cur=[None]*(2*n),idx=0):

如果b->List[str]:
递归(f,b,cur)
的语法,因为代码中没有定义List,区域中也没有定义cur

现在让我们看看第一部分中的代码

def generateParenthesis(n: int) -> List[str]:

    def recursion(f, b, cur=[]):

        if len(cur)==(n*2):
            a ="".join(cur)
            output.append(a)
            return
        if f:
            cur.append("(")
            recursion(f-1,b, cur)
        if b:
            cur.append(")")
            recursion(f,b-1, cur)
    output = []
    f = n
    b = n
    recursion(f, b, cur)

    return output
变量
cur
in通过引用传递到递归。这意味着,所有被调用的递归共享相同的
cur
变量。因此在执行过程中,一旦生成了
“(())”
,其他递归仍然会增加
cur
的长度,使得
“(())”
成为唯一的输出。所以如果你。将条件更改为
,如果len(cur)>=n*2
,您将得到以下输出

['((())'、'((()))'、'((()())'、'(((())))]]

为了使代码正常工作,一种简单的方法是每次调用递归时创建一个新列表。例如,
递归(f-1,b,deepcopy(cur))
,其中
deepcopy
是来自copy import deepcopy
。但我相信在这种情况下,您更愿意使用不可变字符串

另一方面,您也可以将列表视为堆栈。每次递归调用都会附加一个括号,这意味着在堆栈中推送一个括号。因此,您还应该在递归调用之后弹出推式括号。尽管在这种情况下,应使用以前的检查条件

由于Python的
列表
类似于C++的
向量
,因此我们可以只维护最后一个元素的索引,而不是实际弹出。修改后的代码应该是

def generateParenthesis(n):

    def recursion(f, b, cur=[None] * (2*n), idx= 0):

        if b < f or b<0 or f<0:
            return

        if idx >= (n*2):
            a ="".join(cur)
            output.append(a)
            return
        if f:
            cur[idx] = "("
            recursion(f-1,b, cur, idx + 1)
        if b:
            cur[idx] = ")"
            recursion(f,b-1, cur, idx + 1)

    output = []
    f = n
    b = n
    recursion(f, b)

    return output
def generateParenthesis(n):
def递归(f,b,cur=[None]*(2*n),idx=0):
如果b
但有趣的是,您的字符串解决方案比@Tony的基于可变列表的解决方案快25%!至少在我的
generateParenthesis(13)
计时中是这样

下面是我的基于字符串的解决方案——它比@Tony的解决方案慢15%,但没有副作用,并且可以转换为基于列表的解决方案,而不会出现危险的默认值。也就是说,您可以将内部递归函数移到它自己的顶级函数,它仍然可以工作:

def parenthesis(n):

    def parenthesis_recursive(k, f, b, current=""):
        if not b >= f >= 0 <= b:
            return []

        if len(current) == k:
            return [current]

        return parenthesis_recursive(k, f - 1, b, current + "(") + parenthesis_recursive(k, f, b - 1, current + ")")

    return parenthesis_recursive(n * 2, n, n)

print(parenthesis(3))
def括号(n):
def括号_递归(k,f,b,current=”“):
如果不是b>=f>=0
我知道字符串是不可变的,所以在字符串中添加“(”是O(N)
只是想避免那样

但有趣的是,您的字符串解决方案比@Tony的基于可变列表的解决方案快25%!至少在我的
generateParenthesis(13)
计时中是这样

下面是我的基于字符串的解决方案——它比@Tony的解决方案慢15%,但没有副作用,并且可以转换为基于列表的解决方案,而不会出现危险的默认值。也就是说,您可以将内部递归函数移到它自己的顶级函数,它仍然可以工作:

def parenthesis(n):

    def parenthesis_recursive(k, f, b, current=""):
        if not b >= f >= 0 <= b:
            return []

        if len(current) == k:
            return [current]

        return parenthesis_recursive(k, f - 1, b, current + "(") + parenthesis_recursive(k, f, b - 1, current + ")")

    return parenthesis_recursive(n * 2, n, n)

print(parenthesis(3))
def括号(n):
def括号_递归(k,f,b,current=”“):

如果不是b>=f>=0,谢谢你的回答。(n:int)->List[str]直接取自Leetcode,它表示输入为整数,返回为列表感谢@cdlane的计时。Python的列表是一个动态数组,所以实现应该改变。谢谢你的回答。(n:int)->List[str]直接取自Leetcode,它表示输入为整数,返回为列表感谢@cdlane的计时。Python的列表是动态数组,因此实现应该更改。感谢您的计时。我已经将列表误用为链接列表。现在我有了chan