繁体   English   中英

如何获取列表中没有连续重复字符的元素的排列数?

[英]How do I get the number of permutations of the elements in a list that do not have consecutive repeating characters?

我想要一组没有连续重复字符的数字的排列数。

如果我有一个输入为(['1', '2', '3'])的 function number_of_permutations ,我希望它返回 6 因为它的排列都没有连续重复的字符。

123、132、213、231、312、321

但是如果我有参数(['1', '4', '1']) ,我希望它返回 2 因为只有两个排列没有连续重复的字符。

141, 141

如何使用递归在 python 中执行此操作?

如果我们可以放弃recursion作为要求,您可以使用itertools.permutations和 O(n) 循环来解决这个问题。 复杂度与计算所有排列保持相同,并且等于优化算法的最坏情况。

from typing import Iterator
import itertools


def number_of_permutations(possibilities: list) -> Iterator:
    for potential in itertools.permutations(possibilities):
        for i, c in enumerate(potential):
            try:
                if c == potential[i+1]:
                    break 
            except IndexError:
                yield potential

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM