java - 组合 Java 性能

标签 java performance combinations

我想以很大的可能性使用这个函数,比如 700 整数,但是这个函数执行的时间太多了。有人有提高性能的想法吗?谢谢:)

public static Set<Set<Integer>> combinations(List<Integer> groupSize, int k) {

    Set<Set<Integer>> allCombos = new HashSet<Set<Integer>> ();
    // base cases for recursion
    if (k == 0) {
        // There is only one combination of size 0, the empty team.
        allCombos.add(new HashSet<Integer>());
        return allCombos;
    }
    if (k > groupSize.size()) {
        // There can be no teams with size larger than the group size,
        // so return allCombos without putting any teams in it.
        return allCombos;
    }

    // Create a copy of the group with one item removed.
    List<Integer> groupWithoutX = new ArrayList<Integer> (groupSize);
    Integer x = groupWithoutX.remove(groupWithoutX.size() - 1);

    Set<Set<Integer>> combosWithoutX = combinations(groupWithoutX, k);
    Set<Set<Integer>> combosWithX = combinations(groupWithoutX, k - 1);
    for (Set<Integer> combo : combosWithX) {
        combo.add(x);
    }
    allCombos.addAll(combosWithoutX);
    allCombos.addAll(combosWithX);
    return allCombos;
}

最佳答案

您需要对返回值使用 Set 的哪些功能?

如果您只需要其中的一些 - 也许只是 iterator()contains(...) - 那么您可以考虑返回一个 Iterator 即时计算组合。

有一个有趣的机制来生成按字典顺序排列的集合的第 n 个组合 here .

关于java - 组合 Java 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886918/

相关文章:

java - Apache/Tomcat服务器中显示汉字

java - 谷歌地图 API v2 有什么问题?

java - JSoup 数据类型错误

android - 添加许多 Overlay 后 MapView 平移和缩放速度很慢

java - if(condition) else or if(condition),使用break时性能有区别吗?

Matlab:如何从2个向量中找到所有可能的组合?

java - 构建词性标注器(词性标注器)

python - Python导入图像的高效方法

Python:生成一个包含 5 列的多值真值表,其中每列可以取一组特定的值

algorithm - 枚举n个球到k个盒子的所有可能分布