Algorithm to generate all combinations of a string

前端 未结 10 1956
日久生厌
日久生厌 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:00

    Simplest way of calculating the possible combinations of strings is here ...

    Mathematically to find R combinations in a given lot of N = NcR

    So what we are finding here is, all possible combinations = Nc0 + Nc1 .... + Ncn = 2 Pow N

    So you get 2 Pow N combinations for given word of length N characters.

    If you represent 1 to (2 Pow N) integers in binary, and place your char in the place where 1 is present, finally you would get the solution.

    Example:

    Input : ABC

    Solution :

    ABC length is 3. So possible combinations 2 Pow 3 = 8

    If 0 - 8 represented in binary

    000 =

    001 = C

    010 = B

    011 = BC

    100 = A

    101 = AC

    110 = AB

    111 = ABC

    all possible combinations are shown above.

提交回复
热议问题