Generate list of all possible permutations of a string

后端 未结 30 2848
故里飘歌
故里飘歌 2020-11-22 15:10

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 l

30条回答
  •  臣服心动
    2020-11-22 15:29

    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)

    Some pseudocode:

    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)
    

    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.

提交回复
热议问题