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).)
我有一个项目列表{a,b,c,d},我需要生成所有可能的组合,
如果我们采取可能性,它应该是,
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)
当阵列大小很大时,有更有效的方法吗?