Calculate total number of combinations of size k in array using recursion in Java?

882 Views Asked by At

I am attempting to write a recursive method that COUNTS the number of combinations of k size in an integer array.

I can easily do this for a known value k (e.g. 3) as so:

    int[] arr = {1,2,3,4};
    int count = 0;
    for(int i = 0; i < arr.length; i++) {
        for(int j = i+1; j < arr.length; j++) {
            for(int k = j+1; k < arr.length; k++) {
                count++;
            }
        }
    }

However, I would like to be able to do this without a known k. I have found methods online that print the combinations using recursion, such as this one: https://www.techiedelight.com/find-distinct-combinations-of-given-length/, but none that count them.

1

There are 1 best solutions below

2
CoopDaddio On

Simple case of modifying the method linked.

public static int recur(int[] A, int i, int k)
{
    int count = 0;

    if (k == 0) {
        count++;
    }

    for (int j = i; j < A.length; j++) {
        count = count + recur(A, j + 1, k - 1);
    }
    return count;
}