All possible combinations of elements

I would like to know a possible algorithm for calculating all possible combinations without repeating, starting from length = 1 to length = N of N elements.

Example:

Elements: 1, 2, 3.

Output:

  1
 2
 3
 12
 thirteen
 23
 123
+4
source share
1 answer

Look at the binary representation of numbers from 0 to 2 ^ n - 1.

n = 3 i Binary Combination CBA 0 000 1 001 A 2 010 B 3 011 AB 4 100 C 5 101 AC 6 110 BC 7 111 ABC 

So, you just need to list the numbers from 1 to 2 ^ n-1 and look at the binary representation to find out which elements to include. If you want them to be ordered by the number of elements after sorting them or generate numbers in order (there are a few examples on SO).

+10
source

All Articles