简体   繁体   English

我的递归生成字符串所有排列的解决方案如何工作?

[英]How does my solution for recursively generating all permutations of a string work?

def permutationString(word):
    print('word', word)
    result = []

    if len(word) == 0:
        result.append('')
        return result

    for i in range(len(word)):
        before = word[0 : i]
        after = word[i + 1 :]
        print('before',before)
        print('after', after)
        partials = permutationString(before + after)
        print(partials)
        for s in partials:
            result.append(word[i] + s)

    return result

This is my solution for generating a permutation for a given string. 这是我为给定字符串生成排列的解决方案。

For an input abc , it gives me ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] which seems to be correct. 对于输入abc ,它给了我['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] ,这似乎是正确的。

My question is, I don't really understand how the magic works. 我的问题是,我不太了解魔术的工作原理。 The code itself is pretty intuitive; 代码本身非常直观。 we just try each character as the first character and then append the permutations. 我们只是尝试将每个字符作为第一个字符,然后附加排列。

But I really don't get how the partials is generated and I am not sure how the solution does not work when we do not do result.append('') when the word is empty. 但我真的不明白该怎么partials产生,我不知道如何当我们不这样做的解决方案不起作用result.append('')时, word是空的。

Is there an intuitive explanation of how the magic works? 是否有关于魔术如何运作的直观解释?

I have a full lengthy answer here . 在这里有一个很长的答案

The shorter answer is that there's only one way to write a sequence with no elements. 简短的答案是,只有一种方法可以编写没有元素的序列。 That is the empty sequence. 那是空序列。 So the list with all the permutations of '' is [''] . 因此,所有''排列的列表是['']

Suppose you got that wrong and return [] instead, that is, no solutions. 假设您错了,然后返回[] ,即没有解决方案。 What would happen then? 那会发生什么呢?

Well, in the inductive case, as you said, you try each element as the first, and put it in front of the solutions for permutations without that element. 好吧,正如您所说的,在归纳情况下,您将每个元素作为第一个尝试,并将其放在没有该元素的置换解决方案的前面。 So consider a sequence with just one element 'x' . 因此,考虑一个只有一个元素'x'的序列。 You are going to put x in front of all the solutions for '' . 你是打算把x中的所有解决方案的前'' If permutations of '' returned [] , that is an empty list with no solutions, then you would have no solutions to put x in front of. 如果''排列返回[] ,这是一个没有解决方案的空列表,那么您将没有解决方案将x放在前面。 It returns [''] though, so you're going to put 'x' in front of that one solution '' . 但是它返回[''] ,因此您将在该解决方案''前面加上'x' ''

Bonus 奖金

Once you think you got it, you may want to try another similar algorithm for calculating permutations. 一旦想到了,您可能想要尝试另一种类似的算法来计算排列。

Try to build all permutations of word selecting only the first element word[0] at each recursive step, and somehow 'combining' it with the solutions for the permutations of word[1:] . 尝试在每个递归步骤中仅选择第一个元素word[0]来构建word所有排列,然后以某种方式将其与word[1:]排列的解决方案“组合”。

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

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