python - C++ 或 Python 中字符串所有排列的算法

标签 python c++ function recursion scramble

我需要用 c++ 或 python 编写一个函数来获取一个字符串并打印所有可以被打乱的选项。例如 - scramble("abc") 将打印 -

abc
acb
bac
bca
cab
cba

当然不会只有单词的长度是3。

最佳答案

在 Python 中,您可以使用 itertools 中方便的排列函数。

from itertools import permutations

def scrambles(word):
    return [''.join(permutation) for permutation in permutations(word)]

或者,这里有一个明确说明的递归置换算法:

def permutations(word):

    if len(word) == 1:
        # the word is one letter long, so this is the base case; there is only one permutation
        return [word]

    # recursively get all permutations of the word after its first letter
    subword_perms = permutations(word[1:])

    # insert the first letter at all possible positions in each of the possible permutations of the rest of the letters
    first_letter = word[0]
    perms = []
    for subword_perm in subword_perms:
        for i in range(len(subword_perm)+1):
            perm = subword_perm[:i] + first_letter + subword_perm[i:]

            # test to make sure permutation wasn't already found (which is possible if some letters are duplicated within the word)
            if perm not in perms:
                perms.append(perm)
    return perms

关于python - C++ 或 Python 中字符串所有排列的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057991/

相关文章:

python - scikit-learn 中的 TFIDFVectorizer 应该如何工作?

python - ctypes:公开 C 中 malloc 的结构数组

python - 对输出文件进行 A-Z 排序

重新编码列表中的变量

python - 将返回变量从一个函数传递/发送到另一个函数

javascript - 使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数仅调用一次

python - Tripadvisor 抓取 'moreLink'

c++ - 在此指针上使用 static_cast 的无限循环

c++ - 具有不同顶点输入类型的多个着色器可以使用相同的顶点缓冲区吗?

c++ 使用单行 m.swap(std::stringstream()); 清除字符串流?