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

 
Previous Approach:

Find all distinct combinations of a given length – I

 
The problem is very similar to the 0/1 knapsack problem, where for each element in a given array, we have two cases:

  1. Consider that element.
  2. Don’t consider that element.

The following C++ solution generates all combinations using the above logic by traversing the array from left to right. If the tuple of the given size is found, print it. To avoid printing permutations, construct each tuple in the same order as array elements. To print only distinct tuples (when input contains repeated elements), sort the array and exclude all adjacent duplicates along with the current item in case 2.

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 following C++ program demonstrates it:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).