递归计算具有最大位移的排列数

问题描述 投票:0回答:1

我创建了一个名为permutations_dist(s,dist)的递归函数。

应该返回字符串的排列数目,而排列中每2个字母之间的距离不超过给定的数目。

一些示例:

permutations_dist("abc", 1) --> 2
permutations_dist("abc", 1000) --> 6
permutations_dist("abcz", 23) --> 4

如何使以下代码更高效?我想使用回溯。

它很快达到了最大递归深度。例如-permutations_dist("abcdefghijkm", 3))

代码:

def permutations_dist(s, dist):
    return len(permutations_dist_helper(s, dist))

def permutations_dist_helper(s, dist):
   if len(s) == 1:
       return [s]

   perm_list = []  # resulting list
   for a in s:
       remaining_elements = [x for x in s if x != a]
       z = permutations_dist_helper(remaining_elements, dist)

       for t in z:
           if abs(ord(a) - ord(t[0])) <= dist:
               perm_list.append([a] + t)

    return perm_list
python python-3.x recursion permutation
1个回答
1
投票

最好使用堆栈来避免超过最大递归深度。下面的代码生成所有两个相邻字符之间最大距离不超过dist

的所有字符串排列
def permutations(s, dist):
    result = set()
    stack = [("", s, 0)]

    while stack:
        cur, remaining, cur_distance = stack.pop(0)

        if remaining:
            candidates = set()
            for i in range(0, len(remaining)):
                m = remaining[i]
                diff = abs(ord(m) - ord(cur[-1])) if cur else 0
                new_distance = max(cur_distance, diff)
                if new_distance <= dist:
                    head = cur + m
                    candidates.add((head, remaining[:i] + remaining[i+1:], new_distance))
            for c in candidates:
                stack.append(c)
        else:
            result.add(cur)

    return result

让我们检查一下计算permutations(“ abcdefghijk”,3)]需要多长时间:]

from time import time
start = time()
dist = len(permutations("abcdefghijk", 3))
end = time()
print("Premutations: {}, execution time: {:05f}".format(dist, end - start))

在我的MacBook上显示

Premutations: 13592, execution time: 0.663339
© www.soinside.com 2019 - 2024. All rights reserved.