相关疑难解决方法(0)

在Java中获取集合的powerset

powerset {1, 2, 3}是:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

假设我有一个SetJava语言:

Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
Set<Set<Integer>> powerSet = getPowerset(mySet);
Run Code Online (Sandbox Code Playgroud)

如何以最佳的复杂度顺序编写函数getPowerset?(我想它可能是O(2 ^ n).)

java algorithm set powerset

85
推荐指数
7
解决办法
7万
查看次数

生成所有可能的组合 - Java

我有一个项目列表{a,b,c,d},我需要生成所有可能的组合,

  • 您可以选择任意数量的项目
  • 订单不重要(ab = ba)
  • 不考虑空集

如果我们采取可能性,它应该是,

n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15
Run Code Online (Sandbox Code Playgroud)

我使用了以下递归方法:

private void countAllCombinations (String input,int idx, String[] options) {
    for(int i = idx ; i < options.length; i++) {
        String output = input + "_" + options[i];
        System.out.println(output);
        countAllCombinations(output,++idx, options);
    }
}

public static void main(String[] args) {
    String arr[] = {"A","B","C","D"};
    for (int i=0;i<arr.length;i++) {
        countAllCombinations(arr[i], i, arr);
    }
}
Run Code Online (Sandbox Code Playgroud)

当阵列大小很大时,有更有效的方法吗?

java combinations

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×2

algorithm ×1

combinations ×1

powerset ×1

set ×1