简体   繁体   中英

Java function to calculate permutations without repeats

I have an ArrayList and I want to find all of the combinations of a given size without repeats inside it with a single function (built in or not). For example:

ArrayList<Integer> numbers = Array.asList(96, 32, 65, 21);
getCombinationsWithoutRepeats(numbers, 2);

Output:

>>> [[96, 32], [96, 65], [96, 21], [32, 65], [32, 21], [65, 21]]

How would I create this function or is there an inbuilt function that does this?

Here is a sample solution, using backtracking. It will generate you all possible permutations of size K and store them in lists field.

List<List<Integer>> lists = new ArrayList<List<Integer>>();

void permutate(int[] arr, int k) {
    internalPermutate(arr, k, 0, 0);
}

void internalPermutate(int[] arr, int k, int step, int index) {
    if (step == k) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < k; i++) {
            list.add(arr[i]);
        }
        lists.add(list);
    }

    for (int i = step + index; i < arr.length; i++) {
        swap(arr, step, i);
        internalPermutate(arr, k, step + 1, i);
        swap(arr, step, i);
    }
}

private void swap(int[] arr, int x, int y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

public static void main(String[] args) {
    new SomeClass().permutate(new int[] { 1, 2, 3, 4 }, 2);
    System.out.println(lists);
}

This solution doesn't deal with situation when we have the same elements in array, but you can just exclude them before permutation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM