例如,我有一个数组["Sam", "Mary", "John"]
我想显示3中选择2的组合。
结果应该是:
[Sam, Mary]
[Sam, John]
[Mary, John]
我已经研究了很多,但仍然知道该怎么做 当然,这个例子只包含3个人 事实上,总人数会更多,例如15
这是我发现的:
Algorithm to return all combinations of k elements from n
What is a good way to implement choose notation in Java?
其中一些只显示nCr的值,但没有给出组合。
答案 0 :(得分:2)
public static int width;
public static void main(String [] args){
String[] array = {"one", "two", "three", "four", "five"};
width = 3;
List<String> list = new ArrayList<String>();
for (int i = 0; i < array.length; i++){
method(array, list, i, 1, "[" + array[i]);
}
System.out.println(list);
}
public static void method(String[] array, List<String> list, int i, int depth, String string){
if (depth == width){
list.add(string + "]");
return;
}
for (int j = i+1; j < array.length; j++){
method(array, list, j, depth+1, string + ", " + array[j]);
}
}
答案 1 :(得分:1)
打印出给定字符串数组(名为array
)的组合(nCr)的简单递归函数:
String[] array = {"Sam", "Mary", "John"};
public void function(int counter, String comb_Str, int r) {
if (r == 0) {
System.out.println(comb_Str);
} else {
for (; counter < array.length; ++counter) {
function(counter + 1, comb_Str + " " + array[counter], r - 1);
}
}
}
使用function(0, "", #r value#)
r值应为&lt; = n value(数组长度)
答案 2 :(得分:0)
这是一些伪代码,可以帮助您开始使用递归解决方案。列表比字符串数组更容易使用,因为您可以轻松地更改它们的大小。此外,一旦你获得了你的组合,你可以迭代它们以显示它们你想要的。然而,尽管考虑这是一个很好的问题,但是组合的数量会很快失控,所以如果你正在处理超过一些结果,那么将它们全部显示给用户将会成为一个坏主意... < / p>
/**
* @param list The list to create all combos for
* @param comboSize The size of the combo lists to build (e.g. 2 for 2 items combos)
* @param startingIndex The starting index to consider (used mainly for recursion). Set to 0 to consider all items.
*/
getAllCombos(list, comboSize, startingIndex){
allCombos;
itemsToConsider = list.length - startingIndex;
if(itemsToConsider >= comboSize){
allCombos = getAllCombos(list, comboSize, startingIndex + 1);
entry = list[startingIndex];
if(comboSize == 1){
singleList;
singleList.add(entry);
allCombos.add(singleList);
} else {
subListCombos = getAllCombos(list, comboSize - 1, i+1);
for(int i = 0; i < subListCombos.length; i++){
subListCombo = subListCombos[i];
subListCombo.add(entry);
allCombos.add(subListCombo);
}
}
}
return allCombos;
}
答案 3 :(得分:0)
这可能并不完美,但它应该让你走上正轨。创建一个函数来获取每个元素的组合。然后你只需循环遍历每个元素并在每个元素上调用你的函数。
int num = 2; //Number of elements per combination
for(int i=0; i <= (array.length - num); i++) {
String comb = "[" + array[i];
comb += getComb(i,num);
comb += "]";
println(comb);
}
String getComb(int i, int num) {
int counter = 1;
String s = "";
while(counter < num) {
s += ", " + array[i+counter];
counter++;
}
return s;
}