【发布时间】:2016-10-16 13:26:06
【问题描述】:
我有一个项目列表 {a,b,c,d},我需要生成所有可能的组合,
- 您可以选择任意数量的项目
- 顺序不重要 (ab = ba)
- 不考虑空集
如果我们考虑可能性,它应该是,
n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15
我使用了以下递归方法:
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);
}
}
当数组很大时,有没有更有效的方法?
【问题讨论】:
-
这是一个指数算法,所以对于 large 数组,无论如何它仍然会很慢。
-
是的,还有更有效的方法。有现成的解决方案(这里在堆栈上)用于从大小为 N 的列表中生成大小为 M 的子集以及用于子集的排列。他们的组合会做你想要的。
-
在您的情况下,组合的数量在 java
Math.pow(2,n)-1中,其中n是您的数组的大小 -
链接的“重复”是一个更复杂、不同的问题
标签: java combinations