繁体   English   中英

Leetcode pronlem 46 在递归函数中传递参数

[英]Leetcode pronlem 46 passing parameter in recursive function

我正在练习 Leetcode 问题 46 并使用递归方式找到数组的所有排列(例如[1,2,3] )。详细信息可以参考此处的视频。

代码如下:

class Solution:
def permute(self,nums):
    answer=[]
    
    def recur(num,answer,s=[]):
        temp_s=[]
        for k in s:
            temp_s.append(k)      #perform deep copy
        if not num:
            answer.append(temp_s)

        else:
            for i in range(len(num)):
                other=[]
                for j in num:
                    other.append(j)
                s.append(num[i])
                other.pop(i)
                recur(other,answer,s)
                s.pop() 
    recur(nums,answer,s=[]) 
    return answer

我的问题是,为什么我需要deepcopy的s在第几行,因为当我并没有实现深拷贝,则结果为空:

class Solution:
def permute(self,nums):
    answer=[]
    
    def recur(num,answer,s=[]):
        if not num:
            answer.append(s)

        else:
            for i in range(len(num)):
                other=[]
                for j in num:
                    other.append(j)
                s.append(num[i])
                other.pop(i)
                recur(other,answer,s)
                s.pop() 
    recur(nums,answer,s=[]) 
    return answer

[[], [], [], [], [], []]

目标是“找到数组的所有排列”。
每个排列只能作为数组的修改副本存储,否则结果只能是其中之一,而不是全部。
解决方案的递归性质阻止了迭代方法,修改数组,输出它然后再次修改。
因此,如果您从不复制初始数组,则无法实现目标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM