Algorithm to generate all combinations of a string

前端 未结 10 1946
日久生厌
日久生厌 2021-02-01 22:47

I found a link online that shows an algorithm to generate all combinations of a string: http://www.mytechinterviews.com/combinations-of-a-string

Algorithm is copied belo

10条回答
  •  醉酒成梦
    2021-02-01 23:14

    It fits very logically. You see what we have here is a recursive algorithm. At each step in position i we put a letter of the string then call the function recursively to put another letter on the next position. However, when we return from recursion, we need to remove the character we put initially, so that we can replace it with the next possible one in the sequence. Example:

    append a on pos 0 -> a
    call recursion
    append a on pos 1 -> aa
    call recursion
    append a on pos 2 -> aaa
    return from recursion
    remove a from pos 2 -> aa
    append b on pos 2 -> aab
    return from recursion
    remove b from pos 2 -> aa
    append c on pos 2 -> aac
    etc.
    

提交回复
热议问题