【发布时间】:2014-03-31 19:42:30
【问题描述】:
所以我知道如何获得组合的大小 - 数组大小(在我的例子中)的阶乘除以想要的数组子集的大小。我遇到的问题是获取组合。到目前为止,我已经阅读了关于 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} 和 {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;
}
我应该如何计算可用子集的可能组合?
【问题讨论】:
-
您要输出一种解决方案还是所有可能的解决方案?
-
所有可能的解决方案都以奇异数组的形式被视为具有元素 ex: 'array = {1,5,2,4}' 的数组,应该返回。上面解释过。
-
输入总是排序的吗?
-
你知道如何用for循环来做,但你不知道如何递归地做?或者你最大的问题是什么?
-
@libik 不,输入的数组并不总是排序的。我遇到的问题是得到所有排列,我只得到前几个。而不是拐弯抹角……这是我遇到困难的递归方面。
标签: java arrays recursion combinations