python通过参考不起作用是什么?

发布于 2025-02-01 04:55:33 字数 1088 浏览 1 评论 0原文

我有一个解决数组排列的解决方案,如下所示:

class Solution:
    
    def permuteHelper(self,li,nums,ji,x):
        if len(ji)==x:
            li.append(ji)
            return
        for i in range(len(nums)):
            ji.append(nums[i])
            self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
            ji.pop()

    def permute(self, nums: List[int]) -> List[List[int]]:
        li = []
        ji = []
        self.permuteHelper(li,nums,ji,len(nums))
        return li

想法是使用另一个数组,该数组在附加的元素之前先跳过原始数组中的每个元素。但是,这样做时,我将获得空列表列表的输出。

在线我看到有人这样做了,除了他们这样做:

class Solution:
    
    def permuteHelper(self,li,nums,ji,x):
        if len(ji)==x:
            li.append(ji)
            return
        for i in range(len(nums)):
            self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)

    def permute(self, nums: List[int]) -> List[List[int]]:
        li = []
        ji = []
        self.permuteHelper(li,nums,ji,len(nums))
        return li

我不知道他们的解决方案为何奏效,而我的解决方案也没有,我的逻辑与他们的逻辑相同,但我不明白差异。有人可以解释为什么第二个工作而第一个效果不起?

I have a solution for generating permutations of an array which is as follows:

class Solution:
    
    def permuteHelper(self,li,nums,ji,x):
        if len(ji)==x:
            li.append(ji)
            return
        for i in range(len(nums)):
            ji.append(nums[i])
            self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
            ji.pop()

    def permute(self, nums: List[int]) -> List[List[int]]:
        li = []
        ji = []
        self.permuteHelper(li,nums,ji,len(nums))
        return li

Idea is to use another array that appends each element from original array one by one skipping before appended elements. But when doing it like this, I am getting an output of list of empty lists.

Online I saw someone do the same except they did it like this:

class Solution:
    
    def permuteHelper(self,li,nums,ji,x):
        if len(ji)==x:
            li.append(ji)
            return
        for i in range(len(nums)):
            self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)

    def permute(self, nums: List[int]) -> List[List[int]]:
        li = []
        ji = []
        self.permuteHelper(li,nums,ji,len(nums))
        return li

I have no idea why their solution worked and mine did not, I had the same logic as theirs but I don't understand the difference. Can someone please explain why the second one worked and the first one did not?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文