【问题标题】:permutations with repetition in python(to don t use set() or uniform() method )在 python 中重复排列(不要使用 set() 或 uniform() 方法)
【发布时间】:2019-04-03 23:06:27
【问题描述】:

我有一个这样的列表:

from itertools import permutations
l = [1,1,1,1,1,1,1,2]

原始列表中重复的“1”条目意味着不同的排列仅取决于“2”在输出中出现的位置;所以只有 8 个不同的排列。但是 permutations() 函数将生成所有 factorial(8)=40320 排列。我知道我可以在事后使用 set() 函数删除重复的输出,但算法仍然是 O(N!),我想要更高效的东西。

【问题讨论】:

标签: python permutation


【解决方案1】:

这里有几个不使用set的有效解决方案,基本上是关于避免插入重复元素。

# To handle duplication, just avoid inserting a number before any of its duplicates.
def permuteUnique1(nums):
    ans = [[]]
    for n in nums:
        new_ans = []
        for l in ans:
            for i in range(len(l) + 1):
                new_ans.append(l[:i] + [n] + l[i:])
                if i < len(l) and l[i] == n: break  # handles duplication
        ans = new_ans
    return ans


# Duplication happens when we insert the duplicated element before and after the same element,
# to eliminate duplicates, just insert only after the same element.
def permuteUnique2(nums):
    if not nums:
        return []
    nums.sort()
    ans = [[]]
    for n in nums:
        new_ans = []
        l = len(ans[-1])
        for seq in ans:
            for i in range(l, -1, -1):
                if i < l and seq[i] == n:
                    break
                new_ans.append(seq[:i] + [n] + seq[i:])
        ans = new_ans
    return ans


# Build the list of permutations one number at a time, insert the number into each already built permutation
# but only before other instances of the same number, never after.
def permuteUnique3(nums):
    perms = [[]]
    for n in nums:
        perms = [p[:i] + [n] + p[i:]
                 for p in perms
                 for i in range((p + [n]).index(n) + 1)]
    return perms


# or as "one-liner" using reduce:
from functools import reduce
def permuteUnique4(nums):
    return reduce(lambda perms, n: [p[:i] + [n] + p[i:]
                                    for p in perms
                                    for i in range((p + [n]).index(n) + 1)],
                  nums, [[]])

您可以在LeetCode 找到更多解决方案和说明。 希望对您有所帮助,如果您还有其他问题,请发表评论。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2017-10-09
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多