我有一个项目列表{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);
}
}
当数组大小较大时,有没有更有效的方法来完成这个任务?
Math.pow(2,n)-1
пјҢе…¶дёӯn
жҳҜжӮЁзҡ„ж•°з»„еӨ§е°ҸгҖӮ - jr593