答案 0 :(得分: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')]
答案 1 :(得分: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
答案 2 :(得分: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