Given an integer array, find all distinct combinations of a given length k.

For example,

Input:  {2, 3, 4}, k = 2
Output: {2, 3}, {2, 4}, {3, 4}
 
 
Input:  {1, 2, 1}, k = 2
Output: {1, 2}, {1, 1}, {2, 1}

The program should print all the distinct combinations, while preserving the relative order of elements as they appear in the array.

Practice this problem

 
We can use recursion to solve this problem. The idea is to add each element to the output and recur for the remaining items with one less element. To avoid printing permutations, construct each tuple in the same order as array elements. Then if the combination of the given size is found, print it.

The following solution in C++, Java, and Python generates all tuples using the above logic by traversing the array from left to right. To print only distinct combinations for inputs containing repeated elements, sort the array and exclude all adjacent duplicate elements from it.

C++


Download  Run Code

Output:

[1, 2]
[1, 3]
[2, 3]

Java


Download  Run Code

Output:

[[1, 2], [2, 3], [1, 3]]

Python


Download  Run Code

Output:

{(1, 2), (2, 3), (1, 3)}

We can also process the array elements from right to left. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

[1, 2]
[1, 3]
[2, 3]

Java


Download  Run Code

Output:

[[2, 3], [1, 2], [1, 3]]

Python


Download  Run Code

Output:

{(2, 3), (1, 2), (1, 3)}

The time complexity of both above-discussed methods is exponential and requires additional space for the recursion (call stack).