【发布时间】:2016-03-04 19:17:02
【问题描述】:
我认为这根本没有效率。我正在尝试创建一个更快的实现(最好是二进制搜索或使用 Sets),但现在这就是我所在的位置。 我不确定它是否相关,但我创建了一个计数变量只是为了查看该方法被调用了多少次。它达到了577次。
这是“子集总和”算法,我必须在其中显示添加到目标总和的所有子集,在本例中为 3165。 没有具体说明这个问题是算法,但我意识到它确实是同一个概念。
我的问题是我怎么知道这个程序的效率如何,方法调用是否是一个指标?
public class SubsetSumAlgorithm {
static int count = 0;
public static void main(String[] args) {
int[] array = {26, 39, 104, 195, 403, 504, 793, 995, 1156, 1673};
System.out.println("COLLECTIONS IN ARRAY THAT ADD TO 3165: ");
findCollections(array, 0, 0, 3165, "");
System.out.println("Method called " + count + " times.");//method calls
}
public static void findCollections(int[] array, int index, int currentPosition, int sum, String collection) {
count++; //<---COUNTING THE METHOD CALLS HERE
if (array.length < index || currentPosition > sum) {
return;
}
//if sum is found, add to subset
for (int i = index; i < array.length; i++) {
if (currentPosition + array[i] == sum) {
System.out.println(collection + " " + array[i]);
}
//otherwise, call the method again
else if (currentPosition + array[i] < sum) {//recursive call
findCollections(array, i + 1, currentPosition + array[i], sum, collection + " " + array[i]);
}
}
}
}
这是输出:
COLLECTIONS IN ARRAY THAT ADD TO 3165:
26 195 793 995 1156
195 504 793 1673
Method called 577 times.
【问题讨论】:
-
我在那篇文章中看到的唯一大 o 计算是 2^n,但那是使用 Sets。
-
这不可避免地会是指数级的时间和缓慢的。如果你找到解决这个问题的有效方法,你将赢得一百万美元,在计算机科学界永远享有盛誉,你将摧毁互联网。
-
@LouisWasserman 哈哈哈!也许有一天。
-
@LouisWasserman 实际上动态规划在伪多项式时间内解决了这个问题。也就是说,仍然存在指数级缓慢的情况,但大多数情况下它会很快返回。事实上,对于不超过集合大小乘以从最小和到最大和的范围的整数。
标签: java algorithm recursion big-o subset-sum