Algorithm to generate all combinations of a string
It balances the first line of the loop body, restoring outstr to what it was at the top of the loop body (by removing the character from instr that was appended).
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.
The call of outstr.deleteCharAt
counters the effect of outstr.append
by deleting the last character of the outstr
.
Each loop iteration proceeds as follows:
- append a character
- print the result
- perform a recursive invocation at the level
i+1
- remove the character we added at step 1