生成字符串所有可能排列的列表 [英] Generate list of all possible permutations of a string

查看:44
本文介绍了生成字符串所有可能排列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何生成长度在 x 和 y 字符之间的字符串的所有可能排列的列表,其中包含一个可变的字符列表.

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

任何语言都可以,但它应该是可移植的.

Any language would work, but it should be portable.

推荐答案

有几种方法可以做到这一点.常用方法使用递归、记忆或动态规划.基本思想是您生成一个长度为 1 的所有字符串的列表,然后在每次迭代中,对于上次迭代中生成的所有字符串,分别添加与字符串中的每个字符连接的字符串.(下面代码中的变量index记录了上次迭代和下一次迭代的开始)

There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration)

一些伪代码:

list = originalString.split('')
index = (0,0)
list = [""]
for iteration n in 1 to y:
  index = (index[1], len(list))
  for string s in list.subset(index[0] to end):
    for character c in originalString:
      list.add(s + c)

然后您需要删除所有长度小于 x 的字符串,它们将是列表中的第一个 (x-1) * len(originalString) 条目.

you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list.

这篇关于生成字符串所有可能排列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆