题目要求
任意给定一个字符串str,生成数的位数n,有序输出位数为n的所有组合
样例输入
321234
3
样例输出
123
124
132
134
142
143
213
214
231
234
241
243
312
314
321
324
341
342
412
413
421
423
431
432
代码实现
def perm(ori, a, b, m):
if a == m:
print("".join(ori[:m]))
for i in range(a, b):
ori[i], ori[a] = ori[a], ori[i]
# 必须使用列表ori的拷贝,否则会出现重复
perm(ori[:], a + 1, b, m)
if __name__ == '__main__':
# 输入一个字符串、生成位数
ss = list(input())
n = int(input())
# set实现去重
st = set()
# 去重
ss = [c for c in ss if c not in st and not st.add(c)]
# 要求 n<=len(ss)
perm(sorted(ss),0,len(ss),n);
其他方法
# 使用库实现更简便
from itertools import combinations, permutations
s1 = input()
s2 = set(s1)
s3 = list(s2)
s3.sort(reverse=True)
for i in permutations(s3,len(s3)):
print("".join(i))
本文介绍了一种算法,用于从给定的字符串中生成指定长度的所有可能组合,并通过Python代码实现。该算法首先对字符串进行排序和去重,然后递归地生成所有组合,最后输出结果。此外,还提供了一种使用Python标准库itertools的简化实现。

1991

被折叠的 条评论
为什么被折叠?



