[英]Print all combinations of size r from an array of size n
I want to solve the following problem: given an array of size n, print all combinations of size r. 我想解决以下问题:给定大小为n的数组,打印大小为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. 据我所知,组合意味着顺序无关紧要,即
{1, 2}
与{2, 1}
相同{2, 1}
因此我们必须处理重复。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.