如何找到一组的所有可能的分裂?

我需要将一组A分成两组B和C,并找到B和C中所有可能的A’元素分裂。

所以当第一个分割大小为2时

[abcd] – > [ab] [cd],[ac] [bd],[cd] [ab] ..

当第一个分割大小为1时

[abcd] – > [b] [acd],[a] [bdc],[d] [abc] ..

知道如何做到这一点?

你可以使用apache commons math util for java。 如果你正在使用maven在pom中添加它的依赖性,否则手动下载并添加jar。

https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Combinations.html

//n is no of elements. k is k-combinations public Combinations(int n, int k) //you can use this method to get every combination public Iterator iterator() 

这将为您提供所有k组合,值将以索引表示。 你需要将索引转换为元素。

如果是数组arr,你可以做arr [i]。 如果是list,list.get(i)

你是说像这样的算法吗? 我写得很快,希望它有所帮助:

 public void split(int s, String list1, String list2){ if(s > list1.length()){ System.err.println("To big s"); return; } if(s == 0){ System.out.println(list2 + " "+ list1); return; } for(int i = 0; i < list1.length(); i++){ String temp = list1.substring(0, i) + list1.substring(i+1, list1.length()); String temp2 = list2 + list1.charAt(i); split(s-1, temp, temp2); } }