【问题标题】:Generating all subsets of a list生成列表的所有子集
【发布时间】:2020-10-03 08:58:27
【问题描述】:

首先请不要将其标记为重复我已经看过另一个问题,但没有一个能解决我的疑问。

我编写了一个代码来为一个看起来像这样的数组生成所有可能的子集,但不幸的是它返回了一个空数组:

def subsets(self, nums: List[int]) -> List[List[int]]:
    def fun(subset,idx,nums, current):
        subset.append(current)
        while idx<len(nums):
            current.append(nums[idx])
            fun(subset, idx+1, nums, current)
            current.pop()
            idx+=1
    nums.sort()
    subset=[]
    fun(subset, 0, nums, [])
    return subset

让我们说nums=[1,2,3]

我想要的结果:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

我得到的结果:[[],[],[],[],[],[],[],[]]

谁能告诉我哪里出错了?

【问题讨论】:

标签: python python-3.x list recursion


【解决方案1】:

我认为您的主要问题是您尝试插入对列表的引用而不是其中的 copy,只需插入一个副本,您的解决方案就可以作为一种魅力:

def subsets( nums):
    def fun(subset,idx,nums, current):
        subset.append(current.copy())
        while idx<len(nums):
            current.append(nums[idx])
            fun(subset, idx+1, nums, current)
            current.pop()
            idx+=1
    nums.sort()
    subset=[]
    fun(subset, 0, nums, [])
    return subset
    
a = subsets([1,2,3])
print(a)

输出:

[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

【讨论】:

  • 谢谢,@YossiLevi。事实证明,您的调整很有帮助!!!!
【解决方案2】:
def f(nums):
l=[]
for i in range(len(nums)):

    l.append(nums[i])
    print(l)
    if l==nums:
        f(nums[1:len(nums)])

f([1,2,3,4,5])

你可以在 func 方法中使用 func。 例如 nums=[1,2,3,4,5]。 如果我们的列表 (l) = nums 那么 nums 将是 [2,3,4,5] 并且我们的代码在最后做同样的事情。(抱歉我的英语不好。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2021-05-10
    • 2013-08-11
    • 2010-12-04
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多