请解释此算法以获取String的所有排列

gra*_*aci 14 python string recursion permutation

以下代码生成字符串的所有排列:

def permutations(word):
    if len(word)<=1:
        return [word]

    #get all permutations of length N-1
    perms=permutations(word[1:])
    char=word[0]
    result=[]
    #iterate over all permutations of length N-1
    for perm in perms:
        #insert the character into every possible location
        for i in range(len(perm)+1):
            result.append(perm[:i] + char + perm[i:])
    return result
Run Code Online (Sandbox Code Playgroud)

你能解释它是如何工作的吗?我不明白递归.

Mar*_*ers 54

算法是:

  • 删除第一个字母
  • 查找剩余字母的所有排列(递归步骤)
  • 重新插入在每个可能位置删除的字母.

递归的基本案例是单个字母.只有一种方法可以置换单个字母.

工作的例子

想象一下起始词是bar.

  • 首先删除b.
  • 找到permatations ar.这给了arra.
  • 对于每个单词,将其b放在每个位置:
    • ar- > bar,abr,arb
    • ra- > bra,rba,rab


tbr*_*y22 7

我已经写出了一个长度为2的字符串和一个长度为3的字符串的步骤.

置换( 'AB')

len('ab') is not <= 1 
perms = permutations of 'b'
len('b') <= 1 so return 'b' in a list
perms = ['b']
char = 'a'
result = []
for 'b' in ['b']:
    for 0 in [0,1]:
        result.append('' + 'a' + 'b')
    for 1 in [0,1]:
        result.append('b' + 'a' + '')
result = ['ab', 'ba'] 
Run Code Online (Sandbox Code Playgroud)

置换( 'ABC')

len('abc') is not <= 1
perms = permutations('bc')
perms = ['bc','cb']
char = 'a'
result =[]
for 'bc' in ['bc','cb']:
    for 0 in [0,1,2]:
        result.append('' + 'a' + 'bc')
    for 1 in [0,1,2]:
        result.append('b' + 'a' + 'c')
    for 2 in [0,1,2]:
        result.append('bc' + 'a' + '') 
for 'cb' in ['bc','cb']:
    for 0 in [0,1,2]:
        result.append('' + 'a' + 'cb')   
    for 1 in [0,1,2]:
        result.append('c' + 'a' + 'b')   
    for 2 in [0,1,2]:
        result.append('cb' + 'a' + '')
result = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']  
Run Code Online (Sandbox Code Playgroud)