I want to solve the following problem: given an array of size n, print all combinations of size r. As far as I know combination means that the order does not matter, ie {1, 2}
is the same as {2, 1}
so we have to deal with repetitions. I tried to solve the problem recursively, but I print the same combination several times. This is my code:
//main method
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int r = 3;
permute(arr, r);
}
//permute function
private static void permute(int[] arr, int r) {
int[] res = new int[r];
doPermute(arr, res, 0, 0, r);
}
//helper function
private static void doPermute(int[] arr, int[] res, int currIndex, int level, int r) {
if(level == r){
printArray(res);
return;
}
for (int i = currIndex; i < arr.length; i++) {
res[level] = arr[currIndex];
doPermute(arr, res, currIndex+1, level+1, r);
doPermute(arr, res, currIndex+1, level, r);
}
}
//print array function
private static void printArray(int[] res) {
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
System.out.println();
}
And this is part of my very long output:
1 2 3
1 2 4
1 2 3
1 2 4
1 3 4
1 3 4
1 2 3
1 2 4
The code produces all combinations, however with many repetitions. Any help will ge appreciated!
Sorry for my previous answer, I just realized that it was so dumb, that's why I tried somethings for you, try to take off the loop :
private static void doPermute(int[] arr, int[] res, int currIndex, int level, int r) {
if(level == r){
printArray(res);
return;
}
if(currIndex<arr.length){
res[level] = arr[currIndex];
doPermute(arr, res, currIndex+1, level+1, r);
doPermute(arr, res, currIndex+1, level, r);
}
}
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.