所以我知道如何获取组合的大小 - 数组大小(在我的例子中)除以所需数组子集大小的阶乘。我遇到的问题是获取组合。到目前为止,我已经阅读了 stackoverflow 上的大部分问题,但一无所获。我认为我发现的问题是我想将创建的组合子集中的元素添加到一起。总的来说,这应该递归完成
所以澄清一下:
int[] array = {1,2,3,4,5};
子集的大小为 2,组合为
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
从这些数据中我想看看子集是否等于 6,那么答案是:{1,5}
and {2,4}
给我留下了一系列{1,5,2,4}
到目前为止我有这个:
public static int[] subset(int[] array, int n, int sum){
// n = size of subsets
// sum = what the sum of the ints in the subsets should be
int count = 0; // used to count values in array later
int[] temp = new temp[array.length]; // will be array returned
if(array.length < n){
return false;
}
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < n; j++) {
int[] subset = new int[n];
System.arraycopy(array, 1, temp, 0, array.length - 1); // should be array moved forward to get new combinations
**// unable to figure how how to compute subsets of the size using recursion so far have something along these lines**
subset[i] = array[i];
subset[i+1] = array[i+1];
for (int k = 0; k < n; k++ ) {
count += subset[k];
}
**end of what I had **
if (j == n && count == sum) {
temp[i] = array[i];
temp[i+1] = array[i+1];
}
}
} subset(temp, n, goal);
return temp;
}
我应该如何计算可用子集的可能组合?