首页 > 解决方案 > 基于递归的python排列算法

问题描述

我尝试实现置换算法。它运作良好。

但是我关于这个算法中的递归的问题

置换函数:

def permutations(word):

return 声明后它如何以及为什么继续工作?

    if len(word) == 1:
        return [word]

   

如果 last perms == ['3'] 它如何返回它如何从 ['3'] 返回到 ['23']?

    perms = permutations(word[1:])
    char = word[0]
    result = []

    for perm in perms:
        for i in range(len(perm) + 1):
            result.append(perm[:i] + char + perm[i:])
    return result

标签: pythonrecursionpermutation

解决方案


我明白了。基于堆栈的递归。这就是为什么它在 return 语句之后继续执行。


推荐阅读