如何找到具有重复项的集合的所有子集? [关闭]

问题描述 投票:-1回答:3

编写代码以查找ABB的所有组合。

答案应该是

A

B

AB

BB

ABB

This lecture展示了如何处理没有重复的子集。我无法在线找到有效的解决方案来解决这个问题。

algorithm language-agnostic
3个回答
1
投票

递归:

def subsets(seq):
    lst = list(seq)
    if lst:
        x = lst.pop()
        yield (x,)
        for sst in subsets(lst):
            yield (x,) + sst
        yield from subsets([y for y in lst if y != x])

>>> list(subsets('aab'))
[('b',), ('b', 'a'), ('b', 'a', 'a'), ('a',), ('a', 'a')]

如果要对输出进行排序,可以修改逻辑以弹出min元素:

def subsets(seq):
    lst = list(seq)
    if lst:
        i = min(range(len(lst)), key=lst.__getitem__)
        x = lst.pop(i)
        yield (x,)
        for sst in subsets(lst):
            yield (x,) + sst
        yield from subsets([y for y in lst if y != x])

>>> list(subsets('ABB'))
[('A',), ('A', 'B'), ('A', 'B', 'B'), ('B',), ('B', 'B')]

0
投票

在Python 3中,使用itertools非常容易

import itertools


s = "ABB"

combinations = []

for i in range(1, len(s)+1):
    for combo in set(itertools.permutations(s, i)):
        combinations.append("".join(combo))

for c in combinations:
    print(c)

这输出:

B
A
AB
BB
BA
BAB
ABB
BBA

0
投票
strin="ABB"
import copy
ans=[]
def appending(index,answer):
    global ans
    if(index<len(strin)):
        answer1=copy.deepcopy(answer)
        answer1.append(strin[index])
        appending(index+1,answer1)
        appending(index+1,answer)
    else:
        if answer not in ans:
            ans.append(answer)
        return
appending(0,[])

for i in ans:
    if i:
        print(''.join(i))

我得到你的输出,希望你发现它有用

ABB
AB
A
BB
B
© www.soinside.com 2019 - 2024. All rights reserved.