Today I will discuss how to get all the combinations of array elements.

First what do you mean by **Combinations** ?

In mathematics, a combination is a way of selecting members from a grouping, such that (unlike permutations) the order of selection does not matter.

–

Let’s see an example : suppose your array contains following three elements :

1,2,3. Then the list of combinations is :

{Empty}

1,

2,

3,

12,

13,

123,

23.

for array length we have 2^3 combinations. Combinations is nothing but a power set. For a set of length n, a power set is of length 2^n. So for a given array of length n, we can have 2^n total combinations, out of which one is empty set.

There are two ways to do this one is recursive approach or iterative approach. We will do recursive approach today.Here is the code for getting all the combinations of array elements.

1 2 3 4 5 6 7 8 9 10 |
List<string> Combinations = new List<string>(); private void PrintAllCombinations(int[] input, int j, string s) { Combinations.Add(s); if (j >= input.Length) return; for (int i = j; i < input.Length; i++) { PrintAllCombinations(input, i + 1, s + input[i].ToString()); } } |