Print all possible combinations of size r, from an array of size n This is my working solution for the following problem: given an array of integers of size n, print all possible combinations of size r.

Before I proceed to the solution, I have the following question: combination means that the order does not matter, right? I.e. printing {1, 2} is the same as {2, 1}, so I want to avoid repetitions?

If yes, here is what I do to avoid printing duplicate combinations: presort the given array arr, and if for some i I have that arr[i] == arr[i+1] I just skip this iteration.

Is my approach correct? Is there better solution?

package recursion;

import java.util.Arrays;

public class Combinations {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 4, 5};
        int r = 3;
        Arrays.sort(arr);
        combine(arr, r);
    }

    private static void combine(int[] arr, int r) {
        int[] res = new int[r];
        doCombine(arr, res, 0, 0, r);
    }



    private static void doCombine(int[] arr, int[] res, int currIndex, int level, int r) {
        if(level == r){
            printArray(res);
            return;
        }
        for (int i = currIndex; i &lt; arr.length; i++) {
            res[level] = arr[i];
            doCombine(arr, res, i+1, level+1, r);
            //way to avoid printing duplicates
            if(i &lt; arr.length-1 &amp;&amp; arr[i] == arr[i+1]){
                i++;
            }
        }
    }

    private static void printArray(int[] res) {
        for (int i = 0; i &lt; res.length; i++) {
            System.out.print(res[i] + " ");
        }
        System.out.println();
    }
}
I think that by avoiding duplicates, you are essentially changing the definition of the question at hand.

If that is indeed the definition of question, then instead of sorting the array and avoiding duplicates, you can simply get rid of the duplicates to begin with by using a set instead of an array:

Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();
for (int i : arr)
    set.add(i);




In addition, for better modularity, I think that you should separate the algorithm itself from the printing:


Create an empty List&lt;List&lt;Integer&gt;&gt; instance
Pass it to the doCombine method, to fill it in with all combinations
Print it in the main method (the combine method looks kind of redundant)