有关获取所有子集的python编码问题

时间:2019-03-31 22:37:49

标签: python recursion subset backtracking

我正在尝试从唯一列表中获取所有子集。我可以使用长度与原始列表相同的空列表来解决此问题。但是当我想使用不带None的空列表作为占位符时,递归开始起不同的作用。

  1. 带空列表且无占位符的解决方案
def all_subsets(input_list):
    subset_list =[]
    subset = [None]*len(input_list)
    helper(input_list, subset, 0)
    return subset_list

def helper(input_list, subset, i):

    #condition
    if i == len(input_list):
        print(subset)

    else:
        # First Case
        subset[i] = None
        helper(input_list, subset, i+1)
        # Second Branch
        subset[i] = input_list[i]
        helper(input_list, subset, i+1)

all_subsets(input_list)

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

  1. 使用完全空的列表添加元素以创建子集时失败
def all_subsets_2(input_list):
    subsets_list =[]
    subset_list =[]
    helper_2(input_list, subsets_list, subset_list, 0)
    return subsets_list


def helper_2(input_list, subsets_list, subset_list, i):

    #condition
    if i == len(input_list):
        subsets_list.append(subset_list)

    else:
        # First Case
        helper_2(input_list, subsets_list, subset_list, i+1)
        # Second Branch
        subset_list.append(input_list[i])
        helper_2(input_list, subsets_list, subset_list, i+1)



print(all_subsets_2(input_list))

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

0 个答案:

没有答案